【发布时间】:2017-04-11 18:49:55
【问题描述】:
我正在构建一个 Web 应用程序,我希望在其中有单独的关注点,即在不同的项目中具有抽象和实现。
为了实现这一点,我尝试实现一个组合根概念,其中所有实现都必须有一个 ICompositionRootComposer 的实例来注册服务、类型等。
public interface ICompositionRootComposer
{
void Compose(ICompositionConfigurator configurator);
}
在构建层次结构中直接引用的项目中,ICompositionRootComposer 的实现被调用,并且服务在底层 IoC 容器中正确注册。
当我尝试在项目中注册服务时出现问题,我在其中设置了一个构建后任务,将构建的 dll 复制到 Web 项目的调试文件夹:
cp -R $(TargetDir)"assembly and symbol name"* $(SolutionDir)src/"webproject path"/bin/Debug/netcoreapp1.1
我正在加载程序集:(灵感:How to load assemblies located in a folder in .net core console app)
internal class AssemblyLoader : AssemblyLoadContext
{
private string folderPath;
internal AssemblyLoader(string folderPath)
{
this.folderPath = Path.GetDirectoryName(folderPath);
}
internal Assembly Load(string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
AssemblyName assemblyName = new AssemblyName(fileInfo.Name.Replace(fileInfo.Extension, string.Empty));
return this.Load(assemblyName);
}
protected override Assembly Load(AssemblyName assemblyName)
{
var dependencyContext = DependencyContext.Default;
var ressource = dependencyContext.CompileLibraries.FirstOrDefault(r => r.Name.Contains(assemblyName.Name));
if(ressource != null)
{
return Assembly.Load(new AssemblyName(ressource.Name));
}
var fileInfo = this.LoadFileInfo(assemblyName.Name);
if(File.Exists(fileInfo.FullName))
{
Assembly assembly = null;
if(this.TryGetAssemblyFromAssemblyName(assemblyName, out assembly))
{
return assembly;
}
return this.LoadFromAssemblyPath(fileInfo.FullName);
}
return Assembly.Load(assemblyName);
}
private FileInfo LoadFileInfo(string assemblyName)
{
string fullPath = Path.Combine(this.folderPath, $"{assemblyName}.dll");
return new FileInfo(fullPath);
}
private bool TryGetAssemblyFromAssemblyName(AssemblyName assemblyName, out Assembly assembly)
{
try
{
assembly = Default.LoadFromAssemblyName(assemblyName);
return true;
}
catch
{
assembly = null;
return false;
}
}
}
有了这个,我可以加载程序集并调用项目ICompositionRootComposer 实现。
但问题是它似乎无法识别我的任何类型。
当调用我的配置器时
configurator.RegisterTransiantService<IFoo, Foo>();
它应该在 IoC 中注册 IFoo 和 Foo。
但是在调试时,我无法获取类型的信息,即通过 Visual Studio Code 的调试控制台中的 typeof(Foo)。
【问题讨论】:
标签: c# asp.net-core .net-core