Monday, May 16, 2011

Unity: passing constructor parameters.

Unity is a dependency injection container from Microsoft. The version 2.0 is now available for download at codeplex: patterns & practices - Unity. You can use it to reduce dependencies in your .NET applications. Say you want to decouple your 'high level' code from the implementation details of the data access. With Unity you can define an interface like IDataContext and register the actual implementation in the Unity container:
var container = new UnityContainer();
container.RegisterType<IDataContext, SqlDataContext>();
In the 'high level' code you don't have to know the concrete type that implements the data access but just the contract: IDataContext. Unity will resolve the implementation you have registered at runtime:
var dataAccess = container.Resolve<IDataContext>();

Pretty easy so far but what if you want to pass a parameter to the constructor of your IDataContext implementation, e.g. a connection string? Just pass the value you want to be injected as a parameter when registering the type:
container.RegisterType<IDataContext, SqlDataContext>(
  new InjectionConstructor(connectionString));
Unity will pass the value you have defined here to a matching constructor of SqlDataContext when you will request an instance of it.

No comments: