我有这些接口:
public interface _IService<T>
{
T Get(int id);
Task<T> SaveAsync(T entity);
Task<bool> DeleteAsync(int id);
}
public interface ICustomerService :
IService<Customer>
{
IEnumerable<Customer> GetMany(IEnumerable<int> ids);
}
Run Code Online (Sandbox Code Playgroud)
我还有一个抽象类和一个具体的类:
public abstract class Service : IDisposable
{
protected readonly IUnitOfWork unitOfWork;
protected Service(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public void Dispose()
{
if (unitOfWork != null)
{
unitOfWork.Dispose();
}
}
}
public class CustomerService : Service, ICustomerService
{
public CustomerService(IUnitOfWork unitOfWork)
: base(unitOfWork)
{ }
//Implementation here...
}
Run Code Online (Sandbox Code Playgroud)
一切都按预期工作.
现在我想添加通用工厂模式来实例化各种服务.所以我试着这样做:
public TService GetService<TService>()
{
object[] args = new object[] { (unitOfWork) };
return (TService)Activator.CreateInstance(typeof(TService), args);
}
Run Code Online (Sandbox Code Playgroud)
用法如下:
var customerService = GetService<ICustomerService>();
Run Code Online (Sandbox Code Playgroud)
但是,抛出以下异常:
找不到类型'ICustomerService'的构造函数.
那么如何从界面中正确实例化一个类呢?
你不能.您将需要一个依赖注入容器,它知道ISomething您想要ConcreteSomething创建的每个容器.类和接口之间的这种连接并没有神奇地建立,只是想象你有两个类实现ISomething.
您可以自己构建该容器,使用接口类型的字典到类类型,然后执行return (TService)Activator.CreateInstance(this.TypeMappings[typeof(TService)], args);或者您可以使用现有的依赖注入容器之一.但是你需要这个映射.