Tag-Archive for ◊ Dependency Injection ◊

Saturday, March 17th, 2012
Unity Auto Registration extends Unity IoC container and provides fluent syntax to configure rules for automatic type registration. You can add Unity Auto Registration package using NuGet package manager.
Using few code lines you can scan specified assemblies and register all types that satisfy the rules. Rules for determining whether to include/exclude type/assembly are predicates so you can use lambda syntax to
specify them or direct method name. For e.g. you can register interfaces, using AsFirstInterfaceOfType() which
will throw an exception if more than one interface is found on a type.  You can also use decorated attributes type to
register types to the container.
For e.g. All my repositories that implement the type
public interface IRepository
{
IEnumerable All();
T One(Funcbool> condition);
IEnumerable All(Funcbool> condition);
void Add(T entity);
void Save(T entity);
void Remove(T entity);
HashSet Context { get; }
}
public class CustomerRepository : BaseRepository<Customer>
{
//Implementation
methods
}
Can be registered as
_container
=
new UnityContainer();
_container.ConfigureAutoRegistration()
.LoadAssembliesFrom(RegistrationAssemblies.AssemblyNames)
.Include(r => r.ImplementsOpenGeneric(typeof(IRepository<>)),
Then.Register().AsFirstInterfaceOfType())
.ApplyAutoRegistration();
Where RegistrationAssemblies.AssemblyNames is a string array of the assemblies to look for types to register.
You can also decorate the types with a common attribute to register types. For e.g. the business logic components in this sample is decorated with the attribute [Logic] as given below
[Logic]
public class CustomerLogic : ICustomerLogic
{
public IEnumerable<Customer> GetAllByName(string name)
{
var repository = IoC.Container.Resolve<IRepository<Customer>>();
return repository.All(c => c.Name.StartsWith(name));
}
}
These types can be registered using the DecoratedWith method as given below.
_container
=
new UnityContainer();
_container.ConfigureAutoRegistration()
.LoadAssembliesFrom(RegistrationAssemblies.AssemblyNames)
.Include(r => r.ImplementsOpenGeneric(typeof(IRepository<>)), Then.Register().AsFirstInterfaceOfType())
.Include(If.DecoratedWith<Logic>, Then.Register().AsFirstInterfaceOfType())
.ApplyAutoRegistration();
Monday, November 28th, 2011

Unity is a lightweight, extensible dependency injection

container with support for nested containers that stores registrations and
mappings between types and can instantiate the appropriate concrete types on
demand. Identification of the registrations in unity can be done using a type
and a name (optional).
You can use unity to register multiple implementations of
the same type and later resolve the actual instance by passing the name for
identifying the actual implementation. In this post we’ll see how to resolve
the instances registered in unity application block conditionally.
For e.g. I have created a sample interface and
implementations as given below
public interface IMyObject
{
string DoSomething();
}
public class MyObjectFirstImplementation : IMyObject
{
public string
DoSomething()
{
return “First”;
}
}
public class MyObjectSecondImplementation : IMyObject
{
public string
DoSomething()
{
return “Second”;
}
}
The registration of these components are done like
container

.RegisterType<IMyObject, MyObjectFirstImplementation>(DependencyRegistrationKeys.FirstImplementation)

.RegisterType<IMyObject, MyObjectSecondImplementation>(DependencyRegistrationKeys.SecondImplementation);
public static class DependencyRegistrationKeys
{
public const string FirstImplementation = “FIRST_IMPLEMENTATION”;
public const string SecondImplementation = “SECOND_IMPLEMENTATION”;
}
The factory class has a create method that accepts and
object key to resolve the actual instances
public class MyObjectFactory
{
public IMyObject
Create(string objectKey)
{
return Container.Instance.Resolve<IMyObject>(objectKey);
}
}
Tests
[TestMethod]
public void
CreateMethodShouldReturnTheObjectImplementationBasedOnConditionPassed()
{
var factory = new MyObjectFactory();
var myObject = factory.Create(DependencyRegistrationKeys.FirstImplementation);
Assert.IsInstanceOfType(myObject, typeof(MyObjectFirstImplementation));
}
Thursday, August 11th, 2011
ASP.NET was not designed with the concepts of DI and IoC in mind. That makes it very difficult to actually configure a website/ application using ASP.NET to use the concepts of IoC and resolve the dependencies when the pages are requested. An easier way to resolve the dependencies on the page will be using the container and requesting for the resolved types for dependencies. A much better approach is to interpret the page creation implementation code in ASP.NET and resolve the dependencies on the Page from there. In this post I’ll show a sample scenario where we’ll intercept the page creation logic and resolve the dependencies on the page using Unity container.
The sample used in this article has views that have dependencies on the respective presenters. The presenters will depend on the service abstractions to do their work.
I have the base presenter and view interface declarations as
public abstract class AppPresenter where T : IAppView
{
public T View
{
get
{
if (HttpContext.Current == null) return DependencyInjection.Container.Resolve();
return (T)HttpContext.Current.Handler;
}
}
public abstract void InitializeViewEvents();
}
public interface IAppView
{
}
For resolving the dependencies on my views, I have created a custom PageHandler implementation which looks like.
public class UnityPageHandlerFactory : PageHandlerFactory
{
public override IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)
{
var view = base.GetHandler(context, requestType, virtualPath, path) as Page;
if (view == null) return view;
DependencyInjection.Container.BuildUp(view.GetType(), view);
return view;
}
}
<httpHandlers>
<add path=*.aspx verb=* type=BlogsPrajeesh.WebForms.DI.UnityPageHandlerFactory />
<!–httpHandlers>
I have created an extension method on the container to register the dependencies while initializing the container
public static class DependencyRegistrations
{
public static void SetupRegistrations(this UnityContainer container)
{
container
.RegisterType<IHomeView, HomeViewNullObject>()
.RegisterType<IHomeService, HomeService>()
.RegisterType<HomePresenter>();
}
}
Later when the container is initialized you can call the SetupRegistrations methods on the container. container.SetupRegistrations();
A sample view – Presenter implementation can be done like.
public partial class Home : Page, IHomeView
{
private HomePresenter _presenter;
public new event EventHandler OnLoad;
[Dependency]
public HomePresenter Presenter
{
set { _presenter = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
_presenter.InitializeViewEvents();
if (OnLoad != null) OnLoad(this, EventArgs.Empty);
lblHello.Text = _presenter.GetMessage();
}
}
public class HomePresenter : AppPresenter<IHomeView>
{
private readonly IHomeService _homeService;
public HomePresenter([Dependency] IHomeService homeService)
{
_homeService = homeService;
}
public string GetMessage()
{
return _homeService.GetMessage();
}
public override void InitializeViewEvents()
{
View.OnLoad += new EventHandler(View_OnLoad);
}
}
Using this kind of an implementation allows you to completely unit test your ASP.NET web application.
[TestMethod]
public void GetMessageShouldRetrieveTheMessageFromTheRegisteredService()
{
var presenter = DependencyInjection.Container.Resolve<HomePresenter>();
Assert.IsFalse(string.IsNullOrEmpty(presenter.GetMessage()));
}
Monday, December 27th, 2010

Auto mocking allows you to get object of the type you want to test without setting up mocks by hand. Using an auto mocker you can create the mock classes with dependencies and the container will automatically resolve the dependencies for you. The auto mocker will also keep track of all the mocks it creates, and allows you to retrieve them if you need to stub a specific behavior. In this post we’ll se how to create an auto mocking container for Moq using Unity.

The container implementation mainly has 2 methods GetMock and Create.

The GetMock is used to get the MocK of the object so that you can setup expectations and behaviours and later use this for verification.

public Mock<T> GetMock<T>(params object[] constructorParameters) where T : class

{

var _mockedObject = (IMocked<T>)this.Create<T>(constructorParameters);

return _mockedObject.Mock;

}

The Mock method is responsible for creating the mock and resolving dependencies

public T Create<T>(params object[] constructorParameters) where T : class

{

if (!_container.IsRegistered<T>())

{

var mockedType = new Mock<T>(constructorParameters).Object;

var resolvedType = _container.BuildUp<T>(mockedType);

Register<T>(resolvedType);

}

return _container.Resolve<T>();

}

Test methods

Customer customer = CreateMockCustomerWithOrder();

var orderRepository = _mockContainer.GetMock<IOrderRepository>()

.Setup(o => o.GetByCustomer(customer)).Returns(customer.Orders);

_mockContainer.Register<IOrderRepository>(_mockContainer.Create<IOrderRepository>());

ICustomerRepository customerRepository = _mockContainer.Create<CustomerRepository>();

customerRepository.Add(customer)

The UnityMockContainer code used in this sample.

public class UnityMockContainer

{

IUnityContainer _container;

public UnityMockContainer()

{

_container = new UnityContainer();

}

public Mock<T> GetMock<T>(params object[] constructorParameters) where T : class

{

var _mockedObject = (IMocked<T>)this.Create<T>(constructorParameters);

return _mockedObject.Mock;

}

public T Create<T>(params object[] constructorParameters) where T : class

{

if (!_container.IsRegistered<T>())

{

var mockedType = new Mock<T>(constructorParameters).Object;

var resolvedType = _container.BuildUp<T>(mockedType);

Register<T>(resolvedType);

}

return _container.Resolve<T>();

}

public T Create<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class

{

if (!_container.IsRegistered<T>())

{

var mockedType = Moq.Mock.Of<T>(expression);

var resolvedType = _container.BuildUp<T>(mockedType);

Register<T>(resolvedType);

}

return _container.Resolve<T>();

}

public void Register<TFrom, TTo>() where TTo : TFrom

{

_container.RegisterType<TFrom, TTo>();

}

public T Resolve<T>()

{

return _container.Resolve<T>();

}

public void Register<TFrom>(TFrom instance)

{

_container.RegisterInstance<TFrom>(instance);

}

}