基本控制器类的属性注入
我试图在派生自我的 BaseController 类的任何控制器上自动设置属性。这是我的 Application_Start
方法中的代码。当我尝试访问 UnitOfWork
属性时,它始终为 null。
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<VesteraTechnologiesContext>().As<IContext>();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<BaseController>()
.OnActivated(c => c.Instance.UnitOfWork = c.Context.Resolve<IUnitOfWork>());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
这是 BaseController 的样子
public class BaseController : Controller
{
public IUnitOfWork UnitOfWork { get; set; }
}
我尝试通过属性而不是通过构造函数来执行此操作的原因是这样我就不必在需要访问 UnitOfWork 的每个控制器中复制构造函数code> 属性,因为构造函数不是继承的。
I'm trying to automatically set a property on any controller that derives from my BaseController
class. Here is the code in my Application_Start
method. The UnitOfWork
property is always null when I try and access it.
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<VesteraTechnologiesContext>().As<IContext>();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<BaseController>()
.OnActivated(c => c.Instance.UnitOfWork = c.Context.Resolve<IUnitOfWork>());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
Here is what the BaseController looks like
public class BaseController : Controller
{
public IUnitOfWork UnitOfWork { get; set; }
}
The reason I'm trying to do this via a property instead on through a constructor is so that I don't have to duplicate the constructor in every controller that needs access to the UnitOfWork
property, since constructors are not inherited.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Autofac 默认情况下注册控制器以使用构造函数注入。要启用 使用 autofac 进行属性注入:您应该使用:
Autofac by default registers the controllers to use constructor injection. To enable property injection with autofac: you should use:
通常,可以按如下方式调用基本构造函数:
Usually, it's possible to call the base constructor as follows: