我的AutoFac实现似乎没有将我的接口的任何具体实例注入我的API控制器。
检查Container对象时,它确实知道UserRepo - 它对它没有任何作用。
使用最新版本的AutoFac(Nuget)和AutoFac / WebAPI以及Autofc / MVC5。
QPainter::setWindow
public class ContainerConfig
{
public static void RegisterContainer()
{
var builder = new ContainerBuilder();
builder.RegisterApiControllers();
//var asm = typeof(IUserRepository).Assembly;
builder.RegisterAssemblyTypes(typeof(UserRepository).Assembly)
.Where(x => x.Name.EndsWith("Repository")).AsImplementedInterfaces();
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver= new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
public class UsersController : ApiController
{
IUserRepository _db;
public UsersController(IUserRepository db)
{
_db = db;
}
}
公共类UserRepository:IUserRepository { DbContext db = null;
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<FindABriefContext>(new DbInit());
ContainerConfig.RegisterContainer();
}
}
答案 0 :(得分:0)
我认为为Web API实现依赖注入的方式与MVC不同。您应该使用AutofacWebApiDependencyResolver而不是使用AutofacDependencyResolver。
var config = GlobalConfiguration.Configuration;
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);