1 回答
TA贡献1886条经验 获得超2个赞
这是一个工作演示:
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 core 项目
配置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"));
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报
