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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...