如何在netcore2中自动添加依赖项

问题描述 投票:0回答:2

我有多对接口和类似的实现

ICategoryService -> CategoryService
ICategoryTypeService -> CategoryTypeService
IOrderService -> OrderService
ILoggingService -> LoggingService

所有的类和接口都在Data.dll中,我像这样循环它。

foreach (var type in serviceAssembly.GetTypes())
{
    if (type.Name.Contains("Repository") && !type.IsInterface && !type.IsGenericType)
    {
        Type interfaceImplement = type.GetInterfaces().SingleOrDefault(t => t.IsGenericType == false);

        if (interfaceImplement != null)
        {
            System.Diagnostics.Debug.WriteLine($"{type.Name} is inherited by {interfaceImplement.Name}");
            services.AddTransient(interfaceImplement, type);
        }
    }
}

我收到这个错误

InvalidOperationException:尝试激活'VietWebSite.Web.Areas.WebApi.Administrator.ValuesController'时,无法解析类型'VietWebSite.Service.ILoggingService'的服务。

但是如果我将我的代码更改为:

services.AddTransient<ILoggingService, LoggingService>();
services.AddTransient<ICategoryService, CategoryService>();
services.AddTransient<ICategoryTypeService, CategoryTypeService>();
services.AddTransient<IOrderService, OrderService>();

请帮忙。

谢谢

c# asp.net-core-2.0
2个回答
0
投票

这是一个有效的演示:

  1. 使用类和接口创建Data库: public interface ICategoryService { string Output(); } public class CategoryService : ICategoryService { public string Output() { return "CategoryService.Output"; } } public interface ILoggingService { string Output(); } public class LoggingService : ILoggingService { public string Output() { return "LoggingService.Output"; } }
  2. Data库引用添加到asp.net核心项目中
  3. Startup.cs一样配置 var serviceAssembly = Assembly.GetAssembly(typeof(CategoryService)); foreach (var type in serviceAssembly.GetTypes()) { if (type.Name.Contains("Service") && !type.IsInterface && !type.IsGenericType) { Type interfaceImplement = type.GetInterfaces().SingleOrDefault(t => t.IsGenericType == false); if (interfaceImplement != null) { System.Diagnostics.Debug.WriteLine($"{type.Name} is inherited by {interfaceImplement.Name}"); services.AddTransient(interfaceImplement, type); } } }
  4. 使用案例: public class HomeController : Controller { private readonly ILoggingService _loggingService; public HomeController(ILoggingService loggingService) { _loggingService = loggingService; } public IActionResult Index() { var result = _loggingService.Output(); return View(); } }

更新:

你的问题是由AppDomain.CurrentDomain.GetAssemblies()只返回加载的程序集引起的,请尝试下面的代码:

//Load Assemblies
//Get All assemblies.
var refAssembyNames = Assembly.GetExecutingAssembly()
    .GetReferencedAssemblies();
//Load referenced assemblies
foreach (var asslembyNames in refAssembyNames)
{
    Assembly.Load(asslembyNames);
}
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
var myAssemblies = assemblies.Where(assem => assem.GetName().Name.Contains("VietWebSite.Data") || assem.GetName().Name.Equals("VietWebSite.Service"));

0
投票

你是如何做到的,这是正确的手动方式。没有一种自动注入内置的依赖关系的方法,但是有一些可用的包,例如AutoFac https://autofac.org/

© www.soinside.com 2019 - 2024. All rights reserved.