ASP.NET AutoFac 依赖注入问题(跨程序集注入问题)
示例一:我一个接口
public interface ITest
{
string Display();
}
public class TestRepository : ITest
{
public string Display()
{
return "AutoFac"
}
}
public class HomeController
{
private ITest test = null;
public HomeController(ITest _test)
{
this.test = _test;
}
}
通过Global.asax.cs文件实现依赖注入
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
#region Autofac注入依赖
var builder = new ContainerBuilder();
SetupResolveRules(builder);
builder.RegisterControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
#endregion
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
private static void SetupResolveRules(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())//应该问题在这句话上面,但是如果全部在一个csproj里面又是对的,等待大神解决
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
}
问题如下 如果上面的接口是一个类库、实现也是一个类库就出错了,如果所有文件都在同一个csproj里面就没错了,如果分层实现就报错:
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MvcApplication2.Controllers.HomeController' can be invoked with the available services and parameters:
Cannot resolve parameter 'Interface.ITest _test' of constructor 'Void .ctor(Interface.ITest)'.