Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...