wd113
wd113

Reputation: 507

Unity container threw ResolutionFailedException when resolve open generic type

I'm using Unity2.0, and try to resolve a open generic type. The classes are defined as follow:

public interface IRepository<T>
{
    void Add(T t);
    void Delete(T t);
    void Save();
}

public class SQLRepository<T> : IRepository<T>
{
    #region IRepository<T> Members
    public void Add(T t)
    {
        Console.WriteLine("SQLRepository.Add()");
    }
    public void Delete(T t)
    {
        Console.WriteLine("SQLRepository.Delete()");
    }
    public void Save()
    {
        Console.WriteLine("SQLRepository.Save()");
    }
    #endregion
}

The config file is like:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <namespace name="UnityTry"/>
  <assembly name="UnityTry"/>

  <container>
    <register type="IRepository[]" mapTo="SQLRepository[]" name="SQLRepo" />
  </container>
</unity>

the code to resolve IRepository:

        IUnityContainer container = new UnityContainer();

        UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Containers.Default.Configure(container);

        IRepository<string> rep = container.Resolve<IRepository<string>>();
        rep.Add("World");

When I run the code, ResolutionFailedException will be raised at line:

IRepository<string> rep = container.Resolve<IRepository<string>>();

The exception message is :

Exception is: InvalidOperationException - The current type, UnityTry.IRepository`1    [System.String], is an interface and cannot be constructed. Are you missing a type mapping?

Anyone has any ideas of what I have done wrong?

Upvotes: 1

Views: 3757

Answers (1)

Randy Levy
Randy Levy

Reputation: 22655

The open generic is registered with a mapping using the name "SQLRepo" but when resolved a name is not supplied so Unity cannot find the mapping. Try resolving by name:

IRepository<string> rep = container.Resolve<IRepository<string>>("SQLRepo");

Upvotes: 1

Related Questions