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

£可爱£侵袭症+ 提交于 2019-12-20 00:59:19

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/33093688/unity-the-current-type-is-an-interface-and-cannot-be-constructed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!