用依赖注入的通用接口解决 Concrete 类 是一个好的设计吗?
Is it a good design to resolve Concrete classes with Generic Interfaces for Dependency Injection?
使用通用接口来实现具体 类 并使用通用接口在容器中解析是否是一个好模式。
我担心的是它是否打破了单一职责原则,或者它是否与实现紧密结合。
例如
//Base Generic Interface
public interface IBaseServiceCrud<T>
{
T Get(string key);
bool Create (T entity);
bool Delete(T Entity);
}
// Implement Concrete Class with Base Interface
public class Order : IBaseServiceCrud<Order>
{ }
public class Product: IBaseServiceCrud<Order>
{ }
//Or Should we have a interface specific to each service
public interface IOrder: IBaseServiceCrud<Order>
{}
//And then Implement by Concrete Class
public class Order : IOrder
{}
在 DI 容器中支持解析通用接口,但我担心基于通用接口解析是一种很好的做法。
以这种方式实现存储库模式并不少见,您可能不会遇到任何问题(另请参阅 Repository Pattern Standardization of methods)。
至于依赖注入,其实并不重要,只要你的依赖注入框架支持就行。你想要的依赖注入是让你的 类 的依赖变得清晰,使用通用接口并不违背这一点。
使用通用接口来实现具体 类 并使用通用接口在容器中解析是否是一个好模式。
我担心的是它是否打破了单一职责原则,或者它是否与实现紧密结合。
例如
//Base Generic Interface
public interface IBaseServiceCrud<T>
{
T Get(string key);
bool Create (T entity);
bool Delete(T Entity);
}
// Implement Concrete Class with Base Interface
public class Order : IBaseServiceCrud<Order>
{ }
public class Product: IBaseServiceCrud<Order>
{ }
//Or Should we have a interface specific to each service
public interface IOrder: IBaseServiceCrud<Order>
{}
//And then Implement by Concrete Class
public class Order : IOrder
{}
在 DI 容器中支持解析通用接口,但我担心基于通用接口解析是一种很好的做法。
以这种方式实现存储库模式并不少见,您可能不会遇到任何问题(另请参阅 Repository Pattern Standardization of methods)。
至于依赖注入,其实并不重要,只要你的依赖注入框架支持就行。你想要的依赖注入是让你的 类 的依赖变得清晰,使用通用接口并不违背这一点。