我正在尝试在我的项目中使用 autofac。因此,在 Mef 中,我可以使用以下代码获取接口的实例:
private static CompositionContainer _container;
public static void Initialize()
{
string path = AppDomain.CurrentDomain.BaseDirectory.Contains(@"\bin") ?
AppDomain.CurrentDomain.BaseDirectory :
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
//DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"), "*.Data*.dll");
DirectoryCatalog catalog = new DirectoryCatalog(path, "*.dll");
_container = new CompositionContainer(catalog);
_container.ComposeParts();
}
private static void CheckContainer()
{
if (_container == null)
{
Initialize();
}
}
public static T GetInstance<T>()
{
CheckContainer();
return _container.GetExportedValue<T>();
}
但是 autofac 对我来说似乎很困惑......我如何使用 autofac 将此功能添加到我的应用程序中?
谢谢
我将该代码更改为:
private static ContainerBuilder _container;
private static IContainer container;
public static void Initialize()
{
_container = new ContainerBuilder();
var logging = Assembly.Load("StarlightFramework.Logging");
_container.RegisterAssemblyTypes(logging);
container = _container.Build();
}
public static T GetInstance<T>()
{
if(container == null)
Initialize();
return container.Resolve<T>();
}
但是这次我收到了这个错误:“无法加载文件或程序集'Autofac,Version=2.6.1.841,Culture=neutral,PublicKeyToken=17863af14b0044da'或其依赖项之一。”
可能是什么问题?