Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Container Resolve

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");

I get error below:

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?

like image 736
Farukh Avatar asked Sep 08 '15 04:09

Farukh


Video Answer


2 Answers

The main issue is that you are not using a named instance for your 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.

like image 167
NightOwl888 Avatar answered Sep 18 '22 05:09

NightOwl888


I figured it out, I needed create named instance for the service and inject constructor, as such:

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

    _container.RegisterType<IBookService, BookService>("BookService", new InjectionConstructor(typeof(BookRepository)));
    _container.RegisterType<IBookService, BookService>("DatabaseService", new InjectionConstructor(typeof(DatabaseRepository)));
}

And resolve it as below:

var service = _container.Resolve<IBookService>("DatabaseService");
like image 32
Farukh Avatar answered Sep 20 '22 05:09

Farukh