在asp.net核心项目中添加服务

时间:2016-06-17 19:59:51

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

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

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,Type type,Type requiredBy,Boolean isDefaultParameterRequired)      在lambda_method(Closure,IServiceProvider,Object [])

1 个答案:

答案 0 :(得分:0)

不幸的是,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<>也应注册到其实施中。