DbContext注册
container.RegisterType<DbContext, MobileEntities>(GetLifetime());
container.RegisterType<DbContext, AuthenticationEntities>("AuthDb", GetLifetime());
通用存储库注册
container.RegisterType(typeof(IReadOnlyRepository<>), typeof(ReadOnlyRepository<>), GetLifetime());
container.RegisterType(typeof(IReadOnlyRepository<>), typeof(ReadOnlyRepository<>), "ReadOnlyAuth", GetLifetime(), new InjectionConstructor(
container.Resolve<DbContext>("AuthDb")
));
上述存储库仅使用DbContext
作为参数。我有多个我想根据提供的泛型参数注入的上下文。 是否可以在Unity配置中注入正确的DbContext类型而不构造或解析它的实例?
container.RegisterType<IUserPermissionService, UserPermissionService>(GetLifetime(), new InjectionConstructor(
container.Resolve<IReadOnlyRepository<Customer>>("ReadOnlyAuth"),
container.Resolve<IReadOnlyRepository<VisitPlan>>("ReadOnlyAuth"),
container.Resolve<IReadOnlyRepository<UserBranch>>("ReadOnlyAuth"),
container.Resolve<IReadOnlyRepository<UserRoute>>("ReadOnlyAuth"),
container.Resolve<IReadOnlyRepository<UserDriverNumber>>("ReadOnlyAuth"),
container.Resolve<IReadOnlyRepository<UserActivity>>("ReadOnlyAuth"),
container.Resolve<IReadOnlyRepository<UserRole>>("ReadOnlyAuth")
));
我是否可以对其进行配置,以便上述Resolve<>
次调用在他们分开注册之前不会执行?即,我是否可以对其进行配置,使其仅在解决“ReadOnlyAuth”请求时执行container.Resolve<DbContext>("AuthDb")
。
答案 0 :(得分:1)
您可以使用ResolvedParameter
InjectionMember
表示您希望稍后解决该值。将创建一个解析器,它将使用名称和类型在解析时获取依赖关系。
container.RegisterType<IUserPermissionService, UserPermissionService>(
GetLifetime(),
new InjectionConstructor(
new ResolvedParameter<IReadOnlyRepository<Customer>>("ReadOnlyAuth"),
new ResolvedParameter<IReadOnlyRepository<VisitPlan>>("ReadOnlyAuth"),
new ResolvedParameter<IReadOnlyRepository<UserBranch>>("ReadOnlyAuth"),
new ResolvedParameter<IReadOnlyRepository<UserRoute>>("ReadOnlyAuth"),
new ResolvedParameter<IReadOnlyRepository<UserDriverNumber>>("ReadOnlyAuth"),
new ResolvedParameter<IReadOnlyRepository<UserActivity>>("ReadOnlyAuth"),
new ResolvedParameter<IReadOnlyRepository<UserRole>>("ReadOnlyAuth")
));
在这些情况下,也可以使用InjectionFactory
:
container.RegisterType<IUserPermissionService, UserPermissionService>(
GetLifetime(),
new InjectionFactory(c =>
{
new UserPermissionService(
c.Resolve<IReadOnlyRepository<Customer>>("ReadOnlyAuth"),
c.Resolve<IReadOnlyRepository<VisitPlan>>("ReadOnlyAuth"),
c.Resolve<IReadOnlyRepository<UserBranch>>("ReadOnlyAuth"),
c.Resolve<IReadOnlyRepository<UserRoute>>("ReadOnlyAuth"),
c.Resolve<IReadOnlyRepository<UserDriverNumber>>("ReadOnlyAuth"),
c.Resolve<IReadOnlyRepository<UserActivity>>("ReadOnlyAuth"),
c.Resolve<IReadOnlyRepository<UserRole>>("ReadOnlyAuth")
}));
如果使用注入工厂,则需要进行编译时检查,以确保构造函数参数的类型正确。