我有多对接口和类似的实现
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>();
请帮忙。
谢谢
这是一个有效的演示:
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";
}
}
Data
库引用添加到asp.net核心项目中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);
}
}
}
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"));
你是如何做到的,这是正确的手动方式。没有一种自动注入内置的依赖关系的方法,但是有一些可用的包,例如AutoFac https://autofac.org/。