我最近一直在使用依賴注入(Unity)來實現我的域層和任何基礎結構關注點之間的低耦合。DI容器代碼組織
我在我的MVC引導程序中結束了與很多的Unity容器代碼。
一個小片段:
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>>()
)
);
有沒有更好的方式來組織呢?
我似乎無法在網上找到任何示例/文章/方向。
我不是一個團結人..但肯定有一種方法來模塊化這些?我覺得有時候Ninject會被寵壞......你可以創建NinjectModule來註冊類型。還有Ninject Conventions Extension ..這樣就不需要像這樣單獨綁定樣板代碼。也許有這樣的Unity的東西? –
可能有(我不是一個團結人)但我似乎無法找到任何東西。 – davenewza