Far*_*ukh 8 c# dependency-injection unity-container
我刚开始使用Unity Container,我的注册看起来像这样:
static void UnityRegister()
{
_container = new UnityContainer();
_container.RegisterType<IBook, Book>();
_container.RegisterType<IBookRepository, BookRepository>("Book");
_container.RegisterType<IBookService, BookService>();
_container.RegisterType<IBookRepository, DatabaseRepository>("Database");
}
Run Code Online (Sandbox Code Playgroud)
现在当我尝试解决这个问题:
var service = _container.Resolve<IBookService>("Database");
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
解决依赖关系失败,type ="UnityConsoleEx.IBookService",name ="Database".在解决时发生异常:例外情况是:InvalidOperationException - 当前类型UnityConsoleEx.IBookService是一个接口,无法构造.你错过了类型映射吗?
At the time of the exception, the container was:
Resolving UnityConsoleEx.IBookService,Database
Run Code Online (Sandbox Code Playgroud)
谁能指出我做错了什么?
Nig*_*888 12
主要问题是您没有使用命名实例BookService.
_container.RegisterType<IBookService, BookService>();
Run Code Online (Sandbox Code Playgroud)
但是您正尝试使用命名实例进行解析.
var service = _container.Resolve<IBookService>("Database");
Run Code Online (Sandbox Code Playgroud)
您需要在没有名称的情况下解析以获取该实例.
var service = _container.Resolve<IBookService>();
Run Code Online (Sandbox Code Playgroud)
但是,从您的示例中不清楚为什么您首先使用命名实例.如果发布服务的构造函数,将更清楚如何使配置工作.