How to Dependency Injection with NHibernate and Autofac in domain layer ?

There are two ways to DI with nhibernate and Autofac in domain layer (Entities) :
1. You can use directly autofacContainerProvider.Resolve().
Pros:
- simple and quickly
Cons :
- strong coupling between IoC and Entities
- cannot create unit tests for domain layer
- don't support with different UI (Wcf, Web, ..)
2. To resolve these cons, we have implemented this solution :
In Global.asax.cs, in Application_Start add this code after builder.Build() :


var builder = new ContainerBuilder();
builder.RegisterType<SomeDependency>();
// ... continue registering dependencies...
// Once you're done registering things, set the container
// provider up with your registrations.
builder.RegisterAssemblyTypes(typeof (ProductEntity).Assembly).InstancePerDependency();
_containerProvider = new ContainerProvider(builder.Build());


Web Application :

Nhibernate.Cfg.Environment.BytecodeProvider
= new AutofacBytecodeProvider
(new ContainerProviderContainer(AutofacContainerProvider)
, new ProxyFactoryFactory()
, new DefaultCollectionTypeFactory());

WCF Application :
Nhibernate.Cfg.Environment.BytecodeProvider
= new AutofacBytecodeProvider(AutofacContainer
, new ProxyFactoryFactory()
, new DefaultCollectionTypeFactory());

In nhibernate.cfg.xml you should use this factory :
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory
, NHibernate.ByteCode.Castle</property>

and in Entities of domain layer, you should declare the repository interfaces in constructors.

No comments:

Post a Comment