【问题标题】:Dependency injection in constructor of controller with using a ControllerFactory in ASP.NET MVC 5在 ASP.NET MVC 5 中使用 ControllerFactory 的控制器构造函数中的依赖注入
【发布时间】:2016-06-18 21:23:29
【问题描述】:

我正在开发 ASP.NET MVC 5 应用程序。我需要在控制器的构造函数中使用参数。 DefaultControllerFactory 无法解决它,我从它继承了我自己的 ControllerFactory:

public class ControllerFactoryProvider : DefaultControllerFactory
{
    public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
    {
        string controllerType = string.Empty;
        IController controller = null;

        // Read Controller Class & Assembly Name from Web.Config
        controllerType = ConfigurationManager.AppSettings[controllerName];

        if (controllerType == null)
            throw new ConfigurationErrorsException("Assembly not configured for controller " + controllerName);
        // Create Controller Instance
        IDataTransmitter _dataTransmitter = new DataTransmitter();
        controller = Activator.CreateInstance(Type.GetType(controllerType), _dataTransmitter) as IController;
        return controller;
    }

    public void ReleaseController(IController controller)
    {
    //This is a sample implementation
    //If pooling is used to write code to return the object to pool
        if (controller is IDisposable)
        {
            (controller as IDisposable).Dispose();
        }
        controller = null;
    }

} 我在 Global.asax 中注册了它:

ControllerBuilder.Current.SetControllerFactory(新 ControllerFactoryProvider());

但是当我运行我的应用程序时,无论使用 DefaultControllerFactory 都没有看到带参数的构造函数。

哪里有错误?

【问题讨论】:

  • 你到底想要什么?向控制器的构造函数添加参数?还是您打算在控制器的解析中执行一些其他类型的逻辑?
  • 我只需要给控制器设置参数。
  • 在这种情况下你不需要重写你的控制器工厂,你只需要插入你喜欢的依赖注入容器,我会在几个小时内发布答案。

标签: asp.net-mvc dependency-injection controller-factory


【解决方案1】:

正如我在 cmets 中所说,没有必要覆盖您的控制器工厂。你只需要插入你喜欢的依赖注入容器。

我没有机会使用 的每个依赖注入容器,但我会尝试给出一个客观的答案。

Ninject

asp.net Mvc 5 项目中设置Ninject 非常简单。

安装 nuget 包

有一个非常方便的nuget package,叫做Ninject.MVC5

你可以安装它:

  • 使用manage nuget packages 对话,或
  • 通过在包管理器控制台中运行 Install-Package Ninject.MVC5

安装Ninject.MVC5 后,您将在App_Start/ 的解决方案中看到一个名为NinjectWebCommon.cs 的新文件。 Here 你可以看到该文件的内容最终会是什么。

连接你的依赖项

现在已经安装了软件包,您想使用 ninject 的 api 注册您的 denpencies。

假设您有一个IFoo 接口及其实现Foo

public interface IFoo
{
    int Bar()
}

public class Foo : IFoo
{
    public int Bar()
    {
        throw new NotImplementedException();
    }
}

NinjectWebCommon 类中,您将告诉ninject 如何解析IFoo 接口:

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IFoo>().To<Foo>();
}

请记住,默认情况下 Ninject 有implicit self binding of concrete types,这意味着

如果您要解析的类型是具体类型(如上面的 Foo),Ninject 将通过一种称为隐式自绑定的机制自动创建默认关联。好像有这样的注册:

Bind<Foo>().To<Foo>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    相关资源
    最近更新 更多