0

我正在开发 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(new ControllerFactoryProvider());

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

我在哪里可以出错?

4

1 回答 1

1

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

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

忍者

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

安装 nuget 包

有一个很方便的nuget package叫做Ninject.MVC5.

你可以安装它:

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

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

连接你的依赖

现在已经安装了包,你想使用 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 具有具体类型的隐式自绑定,这意味着

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

Bind<Foo>().To<Foo>();
于 2016-03-06T01:02:49.367 回答