基础类中的Autofac属性注入 [英] Autofac property injection in base class
问题描述
我正在使用Windows Phone 8.1应用程序,并且具有具有公共属性的基类.
I am working on a Windows Phone 8.1 application and I have a base class with public property.
public class ViewModelBase
{
public ISomeClass MyProp {get;set;}
}
我的派生类如下
public class MainViewModel : ViewModelBase
{
private readonly INavigation _navigation;
public MainViewModel(INavigation navigation)
{
_navigation = navigation;
}
}
在我的App.cs中,我有
In my App.cs I have
var builder = new ContainerBuilder();
builder.RegisterType<Navigation>().As<INavigation>();
builder.RegisterType<SomeClass>().As<ISomeClass>();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
创建MainViewModel时,我的INavigation已解决,但MyProp为空.我尝试过
When MainViewModel is created my INavigation is resolved but MyProp is null. I have tried
builder.Register(c => new ViewModelBase { MyProp = c.Resolve<ISomeClass>() });
builder.Register(c => new ViewModelBase()).OnActivated(e => e.Instance.MyProp = e.Context.Resolve<ISomeClass>());
builder.RegisterType<ViewModelBase>().PropertiesAutowired();
但没有一个起作用!
解决方案在这里发布 http://bling.github.io/blog/2009/09/07/member-injection-module-for-autofac/
有效,但我不喜欢它:)
works but I don't like it :)
在这种情况下,我不想使用构造函数注入.
I don't want to use constructor injection in this case.
谢谢.
推荐答案
您必须确保您的viewmodel类 MainViewModel
已在属性注入中注册.当前,您向属性注入注册的所有内容都是 ViewModelBase
,但请考虑一下您正在解析.您永远都不会解析 ViewModelBase
,而是要解析 MainViewModel
.这就是需要在容器中注册的内容.
You must make sure that your viewmodel class, MainViewModel
, is registered with property injection. Currently, all you have registered with property injection is ViewModelBase
, but think about what you are resolving. You will never resolve ViewModelBase
, you're resolving MainViewModel
s. So that is what needs to be registered in the container.
尝试:
builder.RegisterType<MainViewModel>().PropertiesAutowired();
这篇关于基础类中的Autofac属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!