开发者

AutoFac creating type regardless of existence

开发者 https://www.devze.com 2023-02-18 23:05 出处:网络
I want to use AutoFac to inject references into an object\'s constructor.However, the actual object itself is not registered.I am doing this for an ASP.NET MVC controller factory, where the controller

I want to use AutoFac to inject references into an object's constructor. However, the actual object itself is not registered. I am doing this for an ASP.NET MVC controller factory, where the controller won't be registered, but the constr开发者_开发知识库uctor params will be. I managed to do this in unity, but I am having trouble with AutoFac.

Is that possible?

Thanks.


To have Autofac resolve any unregistered type the way Unity does:

builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());

An early version of this solution is described here.

However, I +1ed Steven's answer and would encourage you to use it rather than the above. With Autofac you're better off using the pre-built MVC integration. It is a piece of cake to set up on MVC3 - see these step-by-step instructions.

Even if you build your own controller factory, life will be more predictable if you don't rely on the 'resolve anything' behaviour :)


Autofac can't resolve a type that hasn't been registered, even when this type is concrete with a single public constructor.

In your situation this problem however can be solved easily, because there is an Mvc3Ingegration package for Autofac that contains a RegisterControllers extension method for the builder. You can use it as follows:

builder.RegisterControllers(typeof(MvcApplication).Assembly);
0

精彩评论

暂无评论...
验证码 换一张
取 消