I have the following architecture:
- Data
Database Layer - WebAPI
Presentation Layer - Resolver
IoC Register Layer - Services
Business Layer
In WebApiConfig.cs(App_Start) i register the unity container the following way:
// Unity Container Resolver
var container = new UnityContainer();
//Registers the repository interface in Resolver(IoC Register Layer)
var UResolver = new UnityRegisterContainer();
UResolver.RegisterContainer(ref container);
//Configures WebAPI DependecyResolver to use UnityResolver
config.DependencyResolver = new UnityResolver(container);
My Resolver(IoC Register Layer):
public class UnityRegisterContainer
{
public void RegisterContainer(ref UnityContainer container)
{
container.RegisterType<IUnitOfWork>(new HierarchicalLifetimeManager());
container.RegisterType<IService>(new HierarchicalLifetimeManager());
}
}
Controller:
public static KeyService KeyLibrary{ get; set; }
// GET api/values
[Route("Keys")]
public IEnumerable<KeyDTO> Get()
{
var Keys = KeyLibrary.GetAllKeys();
return Keys;
}
KeyService:
public class KeyService: IService
{
IUnitOfWork UOW { get; set; }
/// <summary>
/// Get all Keys
/// </summary>
/// <returns></returns>
public IEnumerable<KeyDTO> GetAllKeys()
{
return Mapper.Map<IEnumerable<Key>, IEnumerable<KeyDTO>>(UOW.Keys.GetAllKeys());
}
}
IService
public interface IService
{
}
IUnitOfWork
public interface IUnitOfWork : IDisposable
{
IKeyRepository Keys { get; }
int Complete();
}
How can i inject the class libraries and repositories with unity?
RegisterContainer, I think the overload you are after is IUnityContainer.RegisterType. So you can call it like this:container.RegisterType<IKeyService, KeyService>(new HierarchicalLifetimeManager());. That is, you will need anIKeyServiceinterface and you'll have to point it to the concrete implementation (if you want to make your mocking/testing life easier) - Andrés RobinetUnityContainerpassed in parameter as aref? I'm not too familiar with the Unit library. Is the container astruct? - gretro