gpt4 book ai didi

c# - 使用 Unity IOC 的 Web API - 如何解决我的 DBContext 依赖关系?

转载 作者:太空狗 更新时间:2023-10-29 23:37:18 25 4
gpt4 key购买 nike

我需要帮助了解 Unity 和 IOC 的工作原理。

我的 UnityContainer 中有这个

var container = new UnityContainer();

// Register types
container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());

config.DependencyResolver = new UnityResolver(container);

然后在我的 Web API Controller 中,我了解到 IService 是由 Unity 注入(inject)的,因为它是一个注册类型。

public class MyController : ApiController
{
private IService _service;

//------- Inject dependency - from Unity 'container.RegisterType'
public MyController(IService service)
{
_service = service;
}

[HttpGet]
public IHttpActionResult Get(int id)
{
var test = _service.GetItemById(id);
return Ok(test);
}
}

我的服务界面

public interface IService
{
Item GetItemById(int id);
}

我的服务实现有自己的构造函数,它接受一个 EntityFramework DBContext 对象。 (EF6)

public class Service : IService
{
private MyDbContext db;

// --- how is this happening!?
public IService(MyDbContext context)
{
// Who is calling this constructor and how is 'context' a newed instance of the DBContext?
db = context;
}

public Item GetItemById(int id)
{
// How is this working and db isn't null?
return db.Items.FirstOrDefault(x => x.EntityId == id);
}
}

最佳答案

它工作的原因是 MyDbContext 有一个无参数的构造函数(或者它有一个包含 unity 可以解析的参数的构造函数),因为默认情况下 unity 可以解析具体类型而无需注册。

引自this reference :

When you attempt to resolve a non-mapped concrete class that does not have a matching registration in the container, Unity will create an instance of that class and populate any dependencies.

您还需要了解 Autowiring 的概念。

当容器尝试解析 MyController 时,它检测到它需要解析映射到 ServiceIService。当容器尝试解析 Service 时,它检测到它需要解析 MyDbContext。此过程称为 Autowiring ,并递归完成,直到创建整个对象图。

关于c# - 使用 Unity IOC 的 Web API - 如何解决我的 DBContext 依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37440568/

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