How to do action injection for MVC 3 using Autofac?

 ̄綄美尐妖づ 提交于 2019-12-04 15:27:08
Nicholas Blumhardt

Action injection is turned off by default in the current Autofac MVC3 implementation.

To enable it, pass a parameter to ExtensibleActionInvoker:

builder.RegisterType<ExtensibleActionInvoker>()
    .As<IActionInvoker>()
    .WithParameter("injectActionMethodParameters", true);

This was quite a recent change and some documentation will need updating - sorry about the hassle.

The problem is this line

builder.Register<ITestInject>(c => new TestInject { TestString = "hi" });

The first parameter in any Register method is the concrete service you want to register. Following that type comes the "how to instantiate", and then parameters that define the actual interface to expose the service as. You get the exception because Autofac tries to instantiate the implementation, which in the case above is an interface. Obviously, no constructor is found on an interface type.

Now look at this:

builder.Register<TestInject>(c => new TestInject { TestString = "hi" }).As<ITestInject>();

This approach IMO is one of Autofacs strengths compared to other DI frameworks. Where others start out the registration with the interface you want to expose and ends up with the implementation, Autofac starts with the actual implementation and ends up with the interface. This makes for cleaner syntax especially in cases where one concrete implementation can be exposed as several interfaces, all in one registration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!