【发布时间】:2014-02-13 11:23:41
【问题描述】:
我最近一直在使用依赖注入 (Unity) 来实现域层与任何基础设施问题之间的低耦合。
我已经在我的 MVC 引导程序中使用了 很多 Unity 容器代码。
一个小sn-p:
container.RegisterType<IUnitOfWork, EntityFrameworkUnitOfWork>("FirstContext", new PerResolveLifetimeManager(), new InjectionConstructor(new FirstContext()));
container.RegisterType<IUnitOfWork, EntityFrameworkUnitOfWork>("AnotherContext", new PerResolveLifetimeManager(), new InjectionConstructor(new AnotherContext()));
// User Aggregate
container.RegisterType<IEntityMapper<User, UserTable>, UserMapper>();
container.RegisterType<IUserRepository, UserRepository>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>("FirstContext"),
new ResolvedParameter<IEntityMapper<User, UserTable>>()
)
);
// Token Aggregate
container.RegisterType<IEntityMapper<Token, TokenTable>, TokenMapper>();
container.RegisterType<ITokenRepository, TokenRepository>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>("FirstContext"),
new ResolvedParameter<IEntityMapper<Token, TokenTable>>()
)
);
// Payment Aggregate
container.RegisterType<IReadOnlyEntityMapper<Payment, PaymentTable>, PaymentFactory>();
container.RegisterType<IPaymentRepository, PaymentRepository>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>("FirstContext"),
new ResolvedParameter<IReadOnlyEntityMapper<Payment, PaymentTable>>()
)
);
// Customer Aggregate
container.RegisterType<IReadOnlyEntityMapper<Customer, CustomerTable>, CustomerMapper>();
container.RegisterType<ICustomerRepository, CustomerRepository>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>("AnotherContext"),
new ResolvedParameter<IReadOnlyEntityMapper<Customer, CustomerTable>>()
)
);
// Country Aggregate
container.RegisterType<IReadOnlyEntityMapper<Country, CountryTable>, CountryMapper>();
container.RegisterType<ICountryRepository, CountryRepository>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>("AnotherContext"),
new ResolvedParameter<IReadOnlyEntityMapper<Country, CountryTable>>()
)
);
// Province Aggregate
container.RegisterType<IReadOnlyEntityMapper<Province, ProvinceTable>, ProvinceMapper>();
container.RegisterType<IProvinceRepository, ProvinceRepository>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>("AnotherContext"),
new ResolvedParameter<IReadOnlyEntityMapper<Province, ProvinceTable>>()
)
);
有没有更好的组织方式?
我似乎在网上找不到任何示例/文章/方向。
【问题讨论】:
-
我不是 Unity 人.. 但肯定有办法将这些模块化吗?有时我会被 Ninject 宠坏了。你可以创建
NinjectModules 来注册类型。还有 Ninject Conventions Extension.. 它消除了像这样单独绑定样板代码的需要。也许 Unity 有类似的东西? -
可能有(我也不是 Unity 人)但我似乎找不到任何东西。
标签: c# dependency-injection domain-driven-design unity-container onion-architecture