当使用 ASP.NET MVC 和实体框架,并尝试实现通用存储库和通用服务,并让 Unity Ioc 解决所有问题时:
我正在尝试让 Unity Ioc 使用参数注入将通用服务注入控制器,但类型解析失败并出现此错误消息:
尝试获取 ISupplierService 类型的实例时发生激活错误当前的构建操作(构建密钥 Build Key[MyApp.Services.Implementation.SupplierService, null])失败:尝试获取 IGenericRepository 类型的实例时发生激活错误
1, key \"\" Resolution of the dependency failed: The current type, MyApp.Repository.Interfaces.IGenericRepository
1[Entities.Supplier ],是一个接口,不能构造。您是否缺少类型映射?(策略类型 BuildPlanStrategy,索引 3)
我可以理解错误消息意味着它正在尝试创建 IGenericRepository 的实例,而我实际上是在尝试让它创建 SupplierService 的实例,但我不明白为什么它会以这种方式解决。根据最初的答案,这可能是因为类型未注册
控制器的服务注入是:
public class SupplierController : Controller
{
private readonly ISupplierService _service;
public SupplierController() : this (null) { }
public SupplierController(ISupplierService service)
{
_service = service;
}
// .. injection fails, service is NULL
}
供应商服务是一个空接口加空类(如果需要,以后可以添加自定义方法)
public partial interface ISupplierService : IGenericService<Supplier> {}
IGenericService 只是重新呈现 IGenericRepository 的方法:
public interface IGenericService<T> : IDisposable where T : BaseEntity {}
在 Global.asax.cs 中,IoC 容器由
var container = new UnityContainer();
var uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
string path = System.IO.Path.GetDirectoryName(uri.AbsolutePath);
var assemblyPaths = new List<string>
{
Path.Combine(path, "MyApp.Repository.Interfaces.dll"),
Path.Combine(path, "MyApp.Repository.Implementation.dll"),
Path.Combine(path, "MyApp.Services.Interfaces.dll"),
Path.Combine(path, "MyApp.Services.Implementation.dll")
};
container
.ConfigureAutoRegistration()
.LoadAssembliesFrom(assemblyPaths)
.ExcludeSystemAssemblies()
.Include(If.Any, Then.Register())
.ApplyAutoRegistration();
var serviceLocator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);