我对DI完全陌生,所以我创建了一个新项目,以了解它在简单项目中的工作方式。 我有BLL项目,只有一个
public interface IService
{
string Method();
}
internal class SomeService : IService
{
public string Method()
{
return "Hi from BLL";
}
}
class BllModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes((Assembly.GetExecutingAssembly())
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
}
}
我想在UI项目中解决此服务。
class Program
{
static void Main(string[] args)
{
//Autofac Configuration
var builder = new ContainerBuilder();
builder.RegisterModule(new BllModule());
var container = builder.Build();
// here i check if container contatins my type (just for debugging), so it has Service BLL.IService
var s = container.ComponentRegistry.Registrations.ToList();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
using (var scope = container.BeginLifetimeScope())
{
// so here i have my exception
var service = scope.Resolve<IService>();
service.Method();
}
}
}
所以使用块抛出的代码
Autofac.Core.Registration.ComponentNotRegisteredException:
"The requested service 'BLL.IService' has not been registered."
我已经更新了代码,现在可以正常工作了