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

后端 未结 1 1025
醉话见心
醉话见心 2021-01-18 23:04

Got below code to start with

public interface IDataContextAsync : IDataContext
{
    Task SaveChangesAsync(CancellationToken cancellationToken);
          


        
相关标签:
1条回答
  • 2021-01-18 23:13

    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.

    0 讨论(0)
提交回复
热议问题