[英]Autofac Property Injection in already registered service
I'm using Autofac to DI and MVVM. 我正在使用Autofac来DI和MVVM。 I have a global service registered as such:
我注册了这样的全球服务:
builder.RegisterType<MyGlobalService>().As<IGlobalService>().SingleInstance();
I'm also using Autofac.Extras.NLog implementation for obvious logging purposes: 我还将Autofac.Extras.NLog实现用于明显的日志记录目的:
builder.RegisterModule<NLogModule>();
this way I can get the instance of that service and logger in any of my ViewModels: 这样,我就可以在任何ViewModel中获取该服务和记录器的实例:
namespace MyNameSpace.ViewModels
{
class MyViewModel : BindableBase
{
readonly IGlobalService _globalService;
readonly ILogger _logger;
public MyViewModel (IGlobalService globalService, ILogger logger)
{
_globalService = globalService;
_logger = logger;
}}}(...)
It works great. 效果很好。 Now I also want logging support inside MyGlobalService.
现在,我还希望在MyGlobalService中记录日志支持。 But this time, I would like to use Property Injection, instead of Constructor Injection.
但是这次,我想使用属性注入,而不是构造函数注入。
Question is: should I register such a rule differently? 问题是:我应该以其他方式注册这样的规则吗?
Example usage: 用法示例:
namespace MyNameSpace.GlobalServices
{
class MyGlobalService : IGlobalService
{
public ILogger Logger { get; set; }
public MyGlobalService ()
{
Logger.Debug("My Service Starting...")
// no DI happening, getting exception because "Logger" is null
}}}(...)
Edit: Answered below. 编辑:下面回答。
Property Injection does not work out-of-the-box, you need to set up class you want to use property injection in, so 属性注入无法立即使用,您需要设置要在其中使用属性注入的类,因此
builder.RegisterType<MyGlobalService>().As<IGlobalService>().PropertiesAutowired().SingleInstance();
should do the trick. 应该可以。 Or you could do this manually using
OnActivating
lifetime event. 或者,您可以使用
OnActivating
生命周期事件手动执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.