我使用这个基本ViewController使用单个服务定位器为所有Xamarin iOS ViewController应用属性注入,而不是使用每个ViewControllers中的静态容器解析依赖关系的常用方法,但是,IsRegistered方法对于ChildViewControllers数组返回true,这当然不是我在Autofac容器中注册的东西,而且在尝试解析它时抛出异常
我如何注册容器:
public static IContainer Container { get; set; }
public static void Register()
{
var builder = new ContainerBuilder();
RegisterDataService(builder);
Container = builder.Build();
}
private static void RegisterDataService(ContainerBuilder builder)
{
builder.Register(c => new ToDoDataServices(new SQLiteConnection(new SQLitePlatformIOS(), path)));
}
以及我如何解决
public class ExtendedViewController : UIViewController
{
public ExtendedViewController(IntPtr ptr) : base(ptr)
{
RegisterDependency();
}
private void RegisterDependency()
{
var type = GetType();
var props = type.GetProperties();
foreach (var prop in props)
{
var propType = prop.PropertyType;
var isRegistered = RegisterComponents.Container.IsRegistered(propType);
if(!isRegistered)
continue;
prop.SetValue(this, RegisterComponents.Container.Resolve(propType));
}
}
}