Using Unity 2 InjectionProperty with an Abstract Base Controller in MVC

I have the following base controller:

public abstract class BaseController : Controller
{
    public IFormsAuthentication FormsAuthentication { get; set; }
    public IAccountRepository AccountRepository { get; set; }
}

I have the following code to install Unity:

.RegisterType<BaseController>(new InjectionProperty[]
    {
        new InjectionProperty("FormsAuthentication", new ResolvedParameter<IFormsAuthentication>()),
        new InjectionProperty("AccountRepository", new ResolvedParameter<IAccountRepository>())
    });

My factory controller is as follows:

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
    return (controllerType == null) ? base.GetControllerInstance(requestContext, controllerType) : container.Resolve<IController>(controllerType);
}

When I try to use AccountRepository from a controller that inherits from the base controller, this setting will not work. I have no problem introducing the constructor in the controller, inheriting from the base controller, but I can not get the injection of properties to work in the base controller. Does anyone know why?

+3
source share
1 answer

I managed to get Setter injection to work on the Controller base class (with Unity.MVC3). I needed to explicitly specify the attribute [Microsoft.Practices.Unity.Dependency]on the base.

:

    [Dependency]
    public IMyServiceDependency MyServiceDependency
    {
        get;
        set;
    }

.

            <register
 type="Project.NameSpace.Interfaces.IMyServiceDependency, Project.NameSpace.Assembly"
 mapTo="Project.NameSpace.MyServiceDependency, Project.NameSpace.Assembly">
            </register>
0

Source: https://habr.com/ru/post/1782843/


All Articles