Xamarin.Forms中Autofac无法识别已存在的构造函数问题求助
I’ve run into this exact issue before with Xamarin.Forms and Autofac—even when a parameterless constructor clearly exists, linker optimizations or cross-platform reflection quirks can cause Autofac to miss it. Here’s how to resolve it:
Common Causes
The most likely reasons for this error are:
- Xamarin Linker Stripping Unused Code: The Xamarin linker removes code it deems unused to reduce app size. Since Autofac uses reflection to instantiate
SqliteManager, the linker might incorrectly flag the parameterless constructor as unused and strip it. - Autofac’s Constructor Finder Needing Explicit Guidance: Sometimes Autofac’s default constructor finder needs a nudge to pick up the parameterless constructor in cross-platform contexts.
Solution 1: Prevent Linker from Stripping the Constructor
Add the [Preserve] attribute to your SqliteManager class or its constructor to tell the linker to retain it.
Update your SqliteManager.cs:
using Xamarin.Forms; public interface ISqliteManager { void test(); } // Preserve all members of the class to avoid missing any required parts [Preserve(AllMembers = true)] public class SqliteManager : ISqliteManager { private readonly string _path; // Alternatively, preserve just the constructor if you prefer // [Preserve] public SqliteManager() { _path = "test"; } public void test() { Console.Write(_path); } }
The [Preserve] attribute is part of Xamarin.Forms, so ensure you include the using Xamarin.Forms; directive.
Solution 2: Explicitly Specify the Parameterless Constructor in Autofac
Tell Autofac exactly which constructor to use by calling UsingConstructor with Type.EmptyTypes (which indicates a parameterless constructor).
Update your registration in ViewModelLocator.cs:
public static void RegisterDependencies() { var builder = new ContainerBuilder(); builder.RegisterType<SqliteManager>() .As<ISqliteManager>() .SingleInstance() .UsingConstructor(Type.EmptyTypes); // Explicitly target the parameterless constructor _container?.Dispose(); _container = builder.Build(); }
Solution 3: Double-Check Public Accessibility
Even though your code looks correct, quickly verify that both the SqliteManager class and its parameterless constructor are marked public. A small typo (like private instead of public) could easily cause this error.
Bonus: Confirm Autofac Compatibility
Ensure you’re using an Autofac version that supports .NET Standard 2.0. Autofac 4.8.0 and later fully support .NET Standard 2.0, so updating from an older version might resolve hidden compatibility issues.
Start with Solution 1—it’s the most common fix for Xamarin-specific linker issues that cause this exact error.
内容的提问来源于stack exchange,提问作者Doc

