Wednesday, December 30, 2009

Unity Application Block – Configuring containers at Run Time


Unity application block also allows you to configure the container and perform injection at run time by directly creating and populating instances of the configuration classes. This provides an alternative approach to using attributes within the target classes or configuring injection requirements using the configuration file.
The RegisterType method allows you to specify the type to be registered in the container and later retrieve it using the Resolve method.
___Container = new UnityContainer()
                .RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();
var __Repository = ___Container.Resolve<IRepository<Employee, Guid>>();
You can also specify the injection constructor for a class either via the InjectionConstructor attribute of through the RegisterType overload that allow configuration injection by accepting InjectionMembers. The constructor defined as InjectionConstructor will be used as the default on while resolving the type.
[InjectionConstructor]
public EmployeeViewModel(IRepository<Employee, Guid> repository)
{
    Repository = repository;
}
[TestInitialize]
public void Initialize()
{
    ___Container = new UnityContainer()
        .RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();           
}

[TestMethod]
public void InjectionConstructor_test()
{
    var __ViewModel = ___Container.Resolve<EmployeeViewModel>();
    Assert.IsNotNull(__ViewModel, "Failed to retrieve ViewModel");
    Assert.IsNotNull(__ViewModel.Repository, "Failed to retrieve Repository");
}

No comments: