我有以下非常简单的带有界面的 ViewModel:
public interface ITestViewModel
{
string Tester { get; }
}
public class TestViewModel : ITestViewModel
{
public string Tester
{
get { return "testing DI"; }
}
}
然后我创建了这个 Autofac 模块:
public class TestModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(c => new TestViewModel()).As<ITestViewModel>();
}
}
ViewModel 和此模块位于一个名为 TestPlugin 的单独 DLL 中。
在我的主应用程序中,我尝试动态加载 TestPlugin 程序集,以便可以将其模块注册到容器中,如下面的代码所示:
var builder = new ContainerBuilder();
var plugins = Directory.EnumerateFiles(@"C:\plugins", "TestPlugin.dll", SearchOption.AllDirectories).ToList();
foreach (var plugin in plugins)
{
var assembly = Assembly.LoadFrom(plugin);
builder.RegisterAssemblyModules(assembly);
}
var container = builder.Build();
var testResolve = container.Resolve<ITestViewModel>();
出于某种原因,虽然我可以清楚地看到服务 ITestViewModel(TestViewModel 的 DelegateActivator)的组件注册,但在 Resolve 调用中仍然收到以下异常:
Autofac.Core.Registration.ComponentNotRegisteredException was unhandled by user code
HResult=-2146233088
Message=The requested service 'TestPlugin.ITestViewModel' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
Source=Autofac
StackTrace:
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context)
at Test.App.<>c__DisplayClass5.<OnStartup>b__0()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
InnerException:
对于为什么会发生这种情况,我们将不胜感激。我的猜测是它与 Assembly.LoadFrom 调用有关,好像我尝试将视图模型/模块拉入主应用程序然后注册似乎正常工作。
谢谢!