我一直在关注非常有用的答案here,使用SimpleInjector DI动态组织我的工作单元和存储库。在SimpleInjector版本3中注册泛型类型
使用下面的测试服务:
public class TestService
{
public TestService(IRepository<Call> calls){}
}
在控制器:
public class TestingController : Controller
{
private readonly IUnitOfWork _unitOfWork ;
public TestingController(IUnitOfWork unitOfWork, TestService testService)
{
_unitOfWork = unitOfWork;
}
}
和引导程序:
public static class BootStrapper
{
public static void ConfigureWeb(Container container)
{
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
container.Options.ConstructorResolutionBehavior = new GreediestConstructorBehavior();
container.Register<DbContext, OCISContext>(Lifestyle.Scoped);
container.Register<ApplicationUserManager>(Lifestyle.Scoped);
container.Register<ApplicationSignInManager>(Lifestyle.Scoped);
container.Register<IAuthenticationManager>(() =>
AdvancedExtensions.IsVerifying(container)
? new OwinContext(new Dictionary<string, object>()).Authentication
: HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);
container.Register<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(Lifestyle.Scoped);
container.Register<IUnitOfWork, UnitOfWork.UnitOfWork>(Lifestyle.Scoped);
container.RegisterCollection(typeof(IRepository<>), typeof(IRepository<>).Assembly);
container.Register<TestService>(Lifestyle.Scoped);
}
我得到的错误:
An exception of type 'System.InvalidOperationException' occurred in SimpleInjector.dll but was not handled in user code
Additional information: The configuration is invalid. Creating the instance for type TestService failed. The constructor of type TestService contains the parameter with name 'calls' and type
IRepository<Call>
that is not registered. Please ensureIRepository<Call>
is registered, or change the constructor of TestService. There is, however, a registration forIEnumerable<IRepository<Call>>
; Did you mean to depend onIEnumerable<IRepository<Call>>
?
我也试过
container.RegisterCollection<IRepository>(new [] {typeof(IRepository)});
container.RegisterCollection(typeof(IRepository), new[] {typeof(IRepository)});
我的目的是让GenericRepository的实例,因为这implents IRepository如在上面的链接的答案。
请更新您的代码并添加相关代码,以说明您在UnitOfWork中注册存储库的原因。 – Steven