【问题标题】:Web API with Unity IOC - How is my DBContext Dependecy resolved?带有 Unity IOC 的 Web API - 如何解决我的 DBContext Dependecy?
【发布时间】:2016-05-25 14:45:01
【问题描述】:

我需要帮助来了解 Unity 以及 IOC 的工作原理。

我的 UnityContainer 中有这个

var container = new UnityContainer();

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

config.DependencyResolver = new UnityResolver(container);

然后在我的 Web API 控制器中,我了解到 IService 是由 Unity 注入的,因为它是一个注册类型。

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 无需注册即可解析具体类。

标签: c# entity-framework asp.net-web-api unity-container


【解决方案1】:

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

引用this reference:

当您尝试解析在容器中没有匹配注册的非映射具体类时,Unity 将创建该类的实例并填充所有依赖项。

您还需要了解自动连线的概念。

当容器尝试解析MyController 时,它检测到它需要解析映射到ServiceIService。当容器尝试解析Service 时,它检测到它需要解析MyDbContext。这个过程称为自动装配,并以递归方式完成,直到创建整个对象图。

【讨论】:

猜你喜欢
  • 2016-02-06
  • 2023-03-24
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
相关资源
最近更新 更多