Unity容器解析 [英] Unity Container Resolve

查看:120
本文介绍了Unity容器解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是从Unity容器开始,注册如下:

I just starting with Unity Container and my registration looks like this:

static void UnityRegister()
{
      _container = new UnityContainer();
      _container.RegisterType<IBook, Book>();
      _container.RegisterType<IBookRepository, BookRepository>("Book");
      _container.RegisterType<IBookService, BookService>();
      _container.RegisterType<IBookRepository, DatabaseRepository>("Database");
}

现在,当我尝试解决此问题时:

Now when I try to resolve doing this:

var service = _container.Resolve<IBookService>("Database");

以下错误:


依赖关系解析失败,类型= UnityConsoleEx.IBookService,名称= Database。
发生以下异常:正在解决。
异常是:InvalidOperationException-当前类型UnityConsoleEx.IBookService是一个接口,无法构造。您是否缺少类型映射?

Resolution of the dependency failed, type = "UnityConsoleEx.IBookService", name = "Database". Exception occurred while: while resolving. Exception is: InvalidOperationException - The current type, UnityConsoleEx.IBookService, is an interface and cannot be constructed. Are you missing a type mapping?



At the time of the exception, the container was:

Resolving UnityConsoleEx.IBookService,Database

任何人都可以指出我在做什么错误?

Can anyone point what I am doing wrong?

推荐答案

主要问题是您没有在 BookService

_container.RegisterType<IBookService, BookService>();

但是您正在尝试使用命名实例进行解析。

But you are trying to resolve with a named instance.

var service = _container.Resolve<IBookService>("Database");

您需要在没有名称的情况下进行解析才能获得该实例。

You need to resolve without a name to get that instance.

var service = _container.Resolve<IBookService>();

但是从您的示例中尚不清楚为什么首先使用命名实例。如果您发布服务的构造函数,则将使如何使配置正常工作变得更加清楚。

But it is unclear from your example why you are using named instances in the first place. If you post the constructors of your services, it will be more clear how to make your configuration work.

这篇关于Unity容器解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆