解析控制器时接口无法构造错误

时间:2017-06-22 08:43:32

标签: asp.net-web-api unity-container

我到处寻找解决方案,但我还没找到。以下是我的招摇错误。

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred when trying to create a controller of type 'TechnicianController'. Make sure that the controller has a parameterless public constructor.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Resolution of the dependency failed, type = \"BackendApp.Controllers.TechnicianController\", name = \"(none)\".\r\nException occurred while: while resolving.\r\nException is: InvalidOperationException - The current type, System.Collections.Generic.IReadOnlyDictionary`2[System.Type,Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsExtension], is an interface and cannot be constructed. Are you missing a type mapping?\r\n-----------------------------------------------\r\nAt the time of the exception, the container was:\r\n\r\n  Resolving BackendApp.Controllers.TechnicianController,(none)\r\n  Resolving parameter \"helper\" of constructor BackendApp.Controllers.TechnicianController(Events_Tenant.Common.Core.Interfaces.ITechnicianRepository technicianRepository, Events_Tenant.Common.Helpers.IHelper helper)\r\n    Resolving Events_Tenant.Common.Helpers.Helper,(none) (mapped from Events_Tenant.Common.Helpers.IHelper, (none))\r\n    Resolving parameter \"tenantsRepository\" of constructor Events_Tenant.Common.Helpers.Helper(Events_Tenant.Common.Core.Interfaces.ICountryRepository countryRepository, Events_Tenant.Common.Core.Interfaces.ITenantsRepository tenantsRepository, Events_Tenant.Common.Core.Interfaces.IProviderRepository venuesRepository, Events_Tenant.Common.Core.Interfaces.IVenueTypesRepository venueTypesRepository)\r\n      Resolving Events_Tenant.Common.Core.Repositories.TenantsRepository,(none) (mapped from Events_Tenant.Common.Core.Interfaces.ITenantsRepository, (none))\r\n      Resolving parameter \"catalogDbContext\" of constructor Events_Tenant.Common.Core.Repositories.TenantsRepository(Events_TenantUserApp.EF.CatalogDB.CatalogDbContext catalogDbContext)\r\n        Resolving Events_TenantUserApp.EF.CatalogDB.CatalogDbContext,(none)\r\n        Resolving parameter \"options\" of constructor Events_TenantUserApp.EF.CatalogDB.CatalogDbContext(Microsoft.EntityFrameworkCore.DbContextOptions`1[[Events_TenantUserApp.EF.CatalogDB.CatalogDbContext, Events-TenantUserApp.EF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] options)\r\n          Resolving Microsoft.EntityFrameworkCore.DbContextOptions`1[Events_TenantUserApp.EF.CatalogDB.CatalogDbContext],(none)\r\n          Resolving parameter \"extensions\" of constructor Microsoft.EntityFrameworkCore.DbContextOptions`1[[Events_TenantUserApp.EF.CatalogDB.CatalogDbContext, Events-TenantUserApp.EF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]](System.Collections.Generic.IReadOnlyDictionary`2[[System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsExtension, Microsoft.EntityFrameworkCore, Version=1.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]] extensions)\r\n            Resolving System.Collections.Generic.IReadOnlyDictionary`2[System.Type,Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsExtension],(none)\r\n",
    "ExceptionType": "Microsoft.Practices.Unity.ResolutionFailedException",
    "StackTrace": "   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)\r\n   at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)\r\n   at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides)\r\n   at Unity.WebApi.UnityDependencyScope.GetService(Type serviceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)",
    "InnerException": {
      "Message": "An error has occurred.",
      "ExceptionMessage": "The current type, System.Collections.Generic.IReadOnlyDictionary`2[System.Type,Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsExtension], is an interface and cannot be constructed. Are you missing a type mapping?",
      "ExceptionType": "System.InvalidOperationException",
      "StackTrace": "   at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)\r\n   at lambda_method(Closure , IBuilderContext )\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)\r\n   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)\r\n   at lambda_method(Closure , IBuilderContext )\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)\r\n   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)\r\n   at lambda_method(Closure , IBuilderContext )\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)\r\n   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)\r\n   at lambda_method(Closure , IBuilderContext )\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)\r\n   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)\r\n   at lambda_method(Closure , IBuilderContext )\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)\r\n   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)\r\n   at lambda_method(Closure , IBuilderContext )\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)\r\n   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)"
    }
  }
}

1 个答案:

答案 0 :(得分:2)

问题是Unity正在尝试解析CatalogDbContext DbContext。默认情况下,Unity将选择参数最多的构造函数。在这种情况下,构造函数是:

public DbContext(DbContextOptions options);

需要一个DbContextOptions对象,因此Unity将再次选择构造函数并尝试实例化任何依赖项,DbContextOptions恰好是IReadOnlyDictionary<Type, IDbContextOptionsExtension>。不幸的是,Unity不知道如何实例化接口IReadOnlyDictionary<Type, IDbContextOptionsExtension>

的具体实例

&#34;确保控制器具有无参数的公共构造函数&#34;当控制器无法实例化时,WebApi提供了一条消息,因为真正发生的事情是非参数化构造函数失败,您可能不想提供无参数构造函数。

以上描述了正在发生的事情。

为什么会发生这种情况是因为    尚未配置控制器所需的依赖项    统一。

如何解决问题不能给出任何细节(旁边    &#34;配置容器&#34;)因为没有代码显示如何    依赖关系已连线。我猜你可能不想对DbContextOptions使用DbContext构造函数重载 - 或许指定Unity使用DbContext的默认构造函数就足够了解决这个问题?

根据以下评论,(至少)有两种方法可以解决问题以填充连接字符串。

选项1 - 连接字符串

注入连接字符串并在DbContext中使用它:

public class CatalogDbContext  : DbContext
{
    private readonly string connectionString;

    public CatalogDbContext (string connectionString)
    {
        this.connectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(this.connectionString);
    }
}

var container = new UnityContainer();
container.RegisterType<CatalogDbContext>(new InjectionConstructor(GetCatalogConnectionString()));

选项2 - 选项生成器

public class CatalogDbContext  : DbContext
{
    public CatalogDbContext(DbContextOptions options)
        : base(options)
    {
    }
}

var container = new UnityContainer();

var contextOptions = new DbContextOptionsBuilder()
    .UseSqlServer(GetCatalogConnectionString())
    .Options;

container.RegisterType<CatalogDbContext>(new InjectionConstructor(contextOptions));