我有一个相当简单的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());