【问题标题】:Adding services in asp.net core project在 asp.net core 项目中添加服务
【发布时间】:2016-10-19 18:15:14
【问题描述】:

有没有办法在一行中将我的所有存储库对象映射到其接口。我不想在这样的声明中重复我自己:

services.AddScoped<Repository.Interfaces.IModeloRepository, Repository.ModeloRepository>();
services.AddScoped<Repository.Interfaces.IMunicipioRepository, Repository.MunicipioRepository>();
services.AddScoped<Repository.Interfaces.IPeriodoRepository, Repository.PeriodoRepository>();
services.AddScoped<Repository.Interfaces.IPlanRepository, Repository.PlanRepository>();

以下是这些存储库之一的声明:

public interface IChatRepository : IRepository<Models.Chat>

我已经尝试过这样的事情:

services.AddScoped(typeof(Repository.Common.IRepository<>), typeof(Repository.Common.BaseRepository<>));

但得到以下错误:

Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0] 发生未处理的异常:尝试激活“SqlExpress.Helpers.LessonTagHelper”时无法解析类型“SqlExpress.Repository.Interfaces.IChatRepository”的服务。 System.InvalidOperationException:尝试激活“SqlExpress.Repository.Interfaces.IChatRepository”时无法解析服务 SqlExpress.Helpers.LessonTagHelper'。 在 Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp,类型类型,类型 requiredBy,布尔 isDefaultParameterRequired) 在 lambda_method(Closure , IServiceProvider , Object[] )

【问题讨论】:

  • 你可以使用反射,但这似乎完全合理......

标签: asp.net-core asp.net-core-mvc


【解决方案1】:

不幸的是,ASP.NET Core 中内置的 DI 容器相对简单。如果您想使用这些更高级的功能,则需要使用不同的容器。

下面的示例使用StructureMap,因为这是我所熟悉的,但 Autofac、Ninject 等可能也可以使用。

将 StructureMap 库添加到 project.json

"StructureMap.Dnx": "0.5.1-rc2-final"

将 DI 容器配置为使用带有命名约定的 StructureMap:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc().AddControllersAsServices();

   // other service configuration

   // Create a new StructureMap container        
   var container = new Container();

   container.Configure(config =>
   {
       //add all the services that are already configured
       config.Populate(services);


       config.Scan(_ =>
       {
          _.WithDefaultConventions();
          _.AssemblyContainingType<Startup>();
          _.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
       });
   });

   //set ASP.NET Core to use the StructureMap container to build types
   return container.GetInstance<IServiceProvider>();
}

值得检查我们的the documentation 以了解其工作原理,但默认约定是自动注册接口类型,例如IMyInterestingType,其实现称为MyInterestingType

通过使用ConnectImplementationsToTypesClosing,每个IRepository&lt;&gt; 也应该注册到它的实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2022-12-06
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多