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 關注
- 111 瀏覽
添加回答
舉報