Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity: The current type is an interface and cannot be constructed

Got below code to start with

public interface IDataContextAsync : IDataContext
{
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
    Task<int> SaveChangesAsync();
}

public partial class DB1Context : DataContext{ }

public partial class DB2Context : DataContext{ }

Below is the UnityConfig file. Note: I am using Nuget bootstrapper for ASP.Net MVC and below is my UnityConfig file

        public static void RegisterTypes(IUnityContainer container)
    {           
        container
            .RegisterType<IDataContextAsync, DB1Context>("DB1Context", new PerRequestLifetimeManager())
            //.RegisterType<IDataContextAsync, DB2Context>("DB2Context", new PerRequestLifetimeManager())
            .RegisterType<IRepositoryProvider, RepositoryProvider>(
                new PerRequestLifetimeManager(),
                new InjectionConstructor(new object[] {new RepositoryFactories()})
            )
            .
            .
            .
            .
    }

And I am getting below error:

The current type, Repository.Pattern.DataContext.IDataContextAsync, is an interface and cannot be constructed. Are you missing a type mapping?

Understand that this named instances is not working with my UnityConfig. Any idea guys?

Thanks in advance

like image 296
DotNetInfo Avatar asked Oct 13 '15 03:10

DotNetInfo


1 Answers

Your service locator that is doing the resolving (after your constructor asks for IDataContextAsync) is probably trying to resolve like this:

Current.Resolve<IDataContextAsync>()

when it needs to resolve like this

Current.Resolve<IDataContextAsync>("DB1Context");

and there wouldn't be any extra logic built into it for it to know that.

If you want to conditionally resolve you could use an injection factory:

   public static class Factory
   {
        public static IDataContextAsync GetDataContext()
        {
            if (DateTime.Now.Hour > 10)
            {
                return new DB1Context();
            }
            else
            {
                return new DB2Context();
            }
        }
    }

..and register IDataContextAsync like this:

Current.RegisterType<IDataContextAsync>(new InjectionFactory(c => Factory.GetDataContext()));

Since it takes a delegate you don't necessarily need the static class / method and could do it inline.

like image 129
CRice Avatar answered Nov 14 '22 23:11

CRice