1

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?

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.