Showing posts with label DI. Show all posts
Showing posts with label DI. Show all posts

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.

Inversion of Control (IoC)

Inversion de contrôle (IoC) est une approche dans le développement de logiciels qui favorise la suppression des dépendances entre les classes pour avoir un code plus simple et plus flexible. Autrement dit, c'est de contrôler la dépendance en dehors de la classe, tout en rendant cette dépendance explicite.
L'utilisation de l'IoC et plus particulièrement l'injection de dépendance (DI) est générallement conçu pour créer des applications qui seront plus flexible, uni-testable, simple et facile à maintenir à long terme. Aujourd'hui, il existe plusieurs IoC en .NET. Parmi les principales, on trouve : Castle Windsor, StructureMap, Spring.NET, Autofac, Unity, Ninject...