Unity Container Resolve

我刚开始使用Unity Container,我的注册看起来像这样:

static void UnityRegister() { _container = new UnityContainer(); _container.RegisterType(); _container.RegisterType("Book"); _container.RegisterType(); _container.RegisterType("Database"); } 

现在当我尝试解决这个问题:

 var service = _container.Resolve("Database"); 

我收到以下错误:

解析依赖关系失败,type =“UnityConsoleEx.IBookService”,name =“Database”。 在解决时发生exception: 例外情况是:InvalidOperationException – 当前类型UnityConsoleEx.IBookService是一个接口,无法构造。 你错过了类型映射吗?

 At the time of the exception, the container was: Resolving UnityConsoleEx.IBookService,Database 

谁能指出我做错了什么?

主要问题是您没有为BookService使用命名实例。

 _container.RegisterType(); 

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

 var service = _container.Resolve("Database"); 

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

 var service = _container.Resolve(); 

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

我想通了,我需要为服务创建命名实例并注入构造函数,如下:

 static void UnityRegister() { _container = new UnityContainer(); _container.RegisterType(); _container.RegisterType(); _container.RegisterType(); _container.RegisterType("BookService", new InjectionConstructor(typeof(BookRepository))); _container.RegisterType("DatabaseService", new InjectionConstructor(typeof(DatabaseRepository))); } 

并解决如下:

 var service = _container.Resolve("DatabaseService"); 

我认为,您尝试使用包含DatabaseRepository作为参数的BookService来解析。 你不能这样做。

你可以这样做:

 var service = _container.Resolve(new ParameterOverride("repository", _container.Resolve("Database"))); 

也许,更好的方法是注册存储库一次,条件:

  _container = new UnityContainer(); _container.RegisterType(); if (useDatabase) { _container.RegisterType(); } else { _container.RegisterType(); } _container.RegisterType(); 

现在,解决服务问题。 此外,您可以像这样配置容器:

 _container.RegisterType( new InjectionConstructor( // Explicitly specify a constructor new ResolvedParameter("Database") // Resolve parameter of type IBookRepository using name "Database" ) ); 

这将告诉容器使用带有单个IBookRepository参数的构造函数来解析IBookService ,并解析名称为Database IBookRepository