C# DependencyResolver的ASP.NET MVC函数
如果我创建自定义控制器工厂,在这种情况下,这行代码意味着什么 依赖解析程序.Current.GetServiceC# DependencyResolver的ASP.NET MVC函数,c#,asp.net-mvc,C#,Asp.net Mvc,如果我创建自定义控制器工厂,在这种情况下,这行代码意味着什么 依赖解析程序.Current.GetService public class CustomControllerFactory : IControllerFactory { public IController CreateController(RequestContext requestContext, string controllerName) { Type targ
public class CustomControllerFactory : IControllerFactory
{
public IController CreateController(RequestContext requestContext, string controllerName)
{
Type targetType = null;
switch (controllerName)
{
case "Product":
targetType = typeof(ProductController);
break;
case "Customer":
targetType = typeof(CustomerController);
break;
default:
requestContext.RouteData.Values["controller"] = "Product";
targetType = typeof(ProductController);
break;
}
return targetType == null ? null :
(IController)DependencyResolver.Current.GetService(targetType); // what this means here ?
}
这一行表示程序员希望当前的依赖项解析器解析指定类型的服务 如果解析器设置正确,它将返回指定类型的实例 您还可以使用通用版本来避免强制转换
另外,我建议不要使用魔术字符串,而是使用枚举或其他强值。这意味着当前依赖项解析程序应该解析targetType的依赖项。从根本上说,这是一个实现
要设置依赖项解析程序,您应该使用
Application\u Start
中的DependencyResolver.SetResolver(myResolver)
,这是服务位置。您正在阅读Adam Freeman吗?是的,我正在阅读Freeman。你读过同一本书吗?