我有以下架构:
在WebApiConfig.cs(App_Start)中,我按以下方式注册统一容器:
// 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);
我的解析器(IoC寄存器层):
public class UnityRegisterContainer
{
public void RegisterContainer(ref UnityContainer container)
{
container.RegisterType<IUnitOfWork>(new HierarchicalLifetimeManager());
container.RegisterType<IService>(new HierarchicalLifetimeManager());
}
}
控制器:
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();
}
如何以统一的方式注入类库和存储库?
答案 0 :(得分:2)
您可以使用构造函数注入,让HttpContext.Current.Request.Form
完成工作并将必要的依赖项传递给类。
DependencyResolver
答案 1 :(得分:2)
虽然首选构造函数注入(有时不建议使用属性注入),但您也可以在具有依赖项的实现类中使用[Dependency]
属性,如下所示:
public class KeyService: IService
{
// Public setter, private getter, so you can mock and manually assing in Unit Tests
[Dependency]
public IUnitOfWork UOW { private get; set; }
public IEnumerable<KeyDTO> GetAllKeys()
{
return Mapper.Map<IEnumerable<Key>, IEnumerable<KeyDTO>>(UOW.Keys.GetAllKeys());
}
}