C#DefaultControllerFactory,支持多个存储库

时间:2015-02-04 14:12:32

标签: c#

我有一个相当简单的DefaultControllerFactory实现,允许将一个存储库注入控制器。

我正在寻求扩展解决方案以允许N个存储库。

我想要实现的是为每个控制器注入不同的存储库。

MyControllerFactory.cs

public class MyControllerFactory : DefaultControllerFactory
{
    private readonly Dictionary<string, Func<RequestContext, IController>> controllers;

    public MyControllerFactory(IRepository repository)
    {
        controllers = new Dictionary<string, Func<RequestContext, IController>>();
        // I want this injected repository to be of type RepA
        controllers["Home"] = controller => new HomeController(repository);
        // I want this injected repository to be of type RepB
        controllers["About"] = controller => new HomeController(repository);
    }

    public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        return this.controllers.ContainsKey(controllerName) ? this.controllers[controllerName](requestContext) : null;
    }
}

我还有一个用于注册的助手类。

这是问题所在。这个类只处理一个存储库,或者我看错了吗?

ControllerFactoryHelper.cs

public static IControllerFactory GetControllerFactory()
{
    string repositoryTypeName = ConfigurationManager.AppSettings["repository"];
    var repositoryType = Type.GetType(repositoryTypeName);
    var repository = Activator.CreateInstance(repositoryType);
    IControllerFactory factory = new MyControllerFactory(repository as IRepository);
    return factory;
}

web.config我有以下密钥:

<add key="repository" value="RepTest.Repository.RepositoryA" />

Global.asax文件中的代码段

ControllerBuilder.Current.SetControllerFactory(ControllerFactoryHelper.GetControllerFactory());

0 个答案:

没有答案