Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

c# - How to inject constructor in controllers by unity on mvc 4

I'm using unity 1.1 version and i couldn't inject constructor. My code sush as:

Registering dependencies in global.asax Application_Startup method:

Core.Instance.Container.RegisterType<ICartBusiness, CartBusiness>();

Injecting constructor:

private ICartBusiness _business;
        public FooController(ICartBusiness business)
        { _business = business; }

mvc throwing this exception:

No parameterless constructor defined for this object.

P.S: i can't use any new version of unity because i'm using too referenced old dlls so i can't use unity.WebApi or unity.Mvc3 dlls.

How to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to tell ASP.MVC to use your container to resolve them.

Create an controller factory like

/// <summary>
/// Controller factory which uses an <see cref="IUnityContainer"/>.
/// </summary>
public class IocControllerFactory : DefaultControllerFactory
{
    private readonly IUnityContainer _container;

    public IocControllerFactory(IUnityContainer container)
    {
        _container = container;
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType != null)
            return _container.Resolve(controllerType) as IController;
        else
            return base.GetControllerInstance(requestContext, controllerType);
    }
}

and register it via the ControllerBuilder in the global.asax

var factory = new IocControllerFactory(_container);
ControllerBuilder.Current.SetControllerFactory(factory);

Every time the framework asks for a new controller it now uses your factory which uses your container.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...