【发布时间】:2019-05-09 06:42:07
【问题描述】:
通过构造函数注入容器是否有效?还是需要更细化?
public class Car{
private readonly IContainer _container;
public Car(IContainer container){
this._container = container;
}
public string DoSomething(){
var service1 =_container.GetInstance<IServiceINeed1>();
service1.DoStuff();
var service2 =_container.GetInstance<IServiceINeed2>();
service2.DoThings();
}
}
对比
public class Car{
private readonly IServiceINeed1 _service1;
private readonly IServiceINeed2 _service2;
public Car(IServiceINeed1 service1, IServiceINeed2 service2){
this._service1 = service1;
this._service2 = service2;
}
public string DoSomething(){
this._service1.DoStuff();
this._service2.DoThings();
}
}
如果无效,背后的原因是什么?
【问题讨论】:
-
我看不出问题出在哪里。您在接口中定义了一些行为。您在接口中注入实现,然后在需要它们的服务中使用它们。
-
这里有多个问题。如果汽车代表和数据实体,它不应该有任何依赖。容器也不应该被注入,容器应该解决其他类的依赖关系。
-
我没有过多关注类名。假设它被称为 SpecialService。另外,禁止容器注入的原因是什么?
标签: c# structuremap