构造函数DI + Unity 2.0 +解决依赖问题

时间:2011-12-05 03:17:24

标签: asp.net-mvc-3 dependency-injection unity-container ioc-container

控制器:

public class HomeController : Controller
{
    IEmployeeTask _employeeTask;

    public HomeController()
    {
        _employeeTask = new UnityContainer().Resolve<IEmployeeTask>();
    }

    public HomeController(IEmployeeTask employeeTask)
    {
        _employeeTask = employeeTask;
    }

    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }       

    public ActionResult GetAndDisplayEmployee()
    {
        return View();
    }

    [HttpPost]
    public ActionResult GetAndDisplayEmployee(int empid)
    {            
        return View(_employeeTask.GetEmployeeModelFromService(empid));            
    }
}

的Global.asax.cs:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    var container = new UnityContainer();
    container.RegisterType<IEmployeeModelMap, EmployeeModelMap>();
    container.RegisterType<IEmployeeService, EmployeeService>();
    container.RegisterType<IEmployeeTask, EmployeeTask>();
    container.RegisterType<IEmployee, Employee>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

Unity依赖性解析器:

 public class UnityDependencyResolver : IDependencyResolver
 {
     readonly IUnityContainer _container;
     public UnityDependencyResolver(IUnityContainer container)
     {
         this._container = container;
     }
     public object GetService(Type serviceType)
     {
         try
         {
             return _container.Resolve(serviceType);
         }
         catch
         {
             return null;
         }
     }
     public IEnumerable<object> GetServices(Type serviceType)
     {
         try
         {
             return _container.ResolveAll(serviceType);
         }
         catch
         {
             return new List<object>();
         }
     }
 }

员工任务类:

 public class EmployeeTask: IEmployeeTask
 {        
     IEmployeeService _employeeService;        
     IEmployeeModelMap _employeeModelMap;

     public EmployeeTask(IEmployeeService employeeService, IEmployeeModelMap employeeModelMap)
     {
         _employeeService = employeeService;
         _employeeModelMap = employeeModelMap;
     }

     public EmployeeViewModel GetEmployeeModelFromService(int empId)
     {
         return _employeeModelMap.ToModel(_employeeService.GetEmployeeFromEntities(empId));
     }
}

现在,我使用了Unity 2.0应用程序块。试图使用单位解决控制器的依赖关系而不使用自定义控制器工厂。      我遇到了以下错误。

  

当前类型DataProviderInfrastructure.IEmployeeTask是一个   界面,不能构造。你错过了类型映射吗?

1 个答案:

答案 0 :(得分:0)

我不使用Unity,但我的猜测是它会尝试使用无参数构造函数来尝试解决依赖关系。创建这个构造函数是非常错误的。首先 - 它失去了依赖注入的目的,第二个 - 你在里面创建了新的容器 - 它将是空的,因此它显然无法解决任何依赖关系。尝试从代码中删除它:

public HomeController()
{
    _employeeTask = new UnityContainer().Resolve<IEmployeeTask>();
}