1 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
這是一個(gè)工作演示:
Data使用類和接口 創(chuàng)建庫:
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 項(xiàng)目
配置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()只會(huì)返回加載的程序集引起的,請(qǐng)嘗試以下代碼:
//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 關(guān)注
- 119 瀏覽
添加回答
舉報(bào)