gpt4 book ai didi

c# - 使用 WebAPI 的 Microsoft Unity 依赖注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-03 21:11:15 25 4
gpt4 key购买 nike

我有以下架构:

  • 数据
    数据库层
  • WebAPI
    表现层
  • 解析器
    IoC 寄存器层
  • 服务
    业务层

在 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());
}
}

Controller :

public static KeyService KeyLibrary{ get; set; }

// GET api/values
[Route("Keys")]
public IEnumerable<KeyDTO> Get()
{
var Keys = KeyLibrary.GetAllKeys();

return Keys;
}

key 服务:

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());
}
}

I服务

public interface IService
{
}

工作单元

public interface IUnitOfWork : IDisposable
{
IKeyRepository Keys { get; }
int Complete();
}

如何统一注入(inject)类库和存储库?

最佳答案

您可以使用构造函数注入(inject)并让 DependencyResolver 完成它的工作并将必要的依赖项传递给类。

public class KeyController : ApiController {
IKeyService keyService;
public KeyController(IKeyService keyService) {
this.keyService = keyService
}

// GET api/values
[Route("Keys")]
public IEnumerable<KeyDTO> Get() {
var Keys = keyService.GetAllKeys();
return Keys;
}
}

public interface IKeyService : IService {
IEnumerable<KeyDTO> GetAllKeys();
}

public class KeyService: IKeyService {
IUnitOfWork UOW;

public KeyService(IUnitOfWork uow) {
this.UOW = uow
}

/// <summary>
/// Get all Keys
/// </summary>
/// <returns></returns>
public IEnumerable<KeyDTO> GetAllKeys() {
return Mapper.Map<IEnumerable<Key>, IEnumerable<KeyDTO>>(UOW.Keys.GetAllKeys());
}
}

public class UnitOfWork: IUnitOfWork {
public UnitOfWork(IKeyRepository repository) {
Keys = repository;
}
IKeyRepository Keys { get;private set }
public int Complete(){...}
}

关于c# - 使用 WebAPI 的 Microsoft Unity 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37534683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com