因为使用webapi所以不能使用构造函数注入,只有进行属性注入,但是一直注入失败,麻烦帮忙看看,谢谢
项目结构图如下
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //Autofac配置 var builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; var assemblyList = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterAssemblyTypes(assemblyList).Where(t => t.Name.Contains("XX")) .Where(t => t.Name.Contains("Service") || t.Name.Contains("Interface")) .AsImplementedInterfaces(); //注册所有的ApiControllers builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); var container = builder.Build(); //注册api容器需要使用HttpConfiguration对象 config.DependencyResolver = new AutofacWebApiDependencyResolver(container); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
使用代码
public class UserController : ApiController { public IUserLoginCacheService UserLoginCacheService { get; set; } [HttpGet] public HttpResponseMessage Test() { var list = UserLoginCacheService.GetEntityByWhere(it => true); return Request.CreateResponse(HttpStatusCode.OK, new { Code = -1, IsResult = false, Msg = "123456" }); } }
UserLoginCacheService对象一直未空,而且在相关的DLL都在webapi目录下
诸如不是要在构造函数中实现的吗?
因为webapi中,如果用构造函数要报错。
public class UserController : ApiController { public IUserLoginCacheService UserLoginCacheService { get; set; } public UserController(IUserLoginCacheService _UserLoginCacheService) { _UserLoginCacheService = UserLoginCacheService; } [HttpGet] public HttpResponseMessage Test() { var list = UserLoginCacheService.GetEntityByWhere(it => true); return Request.CreateResponse(HttpStatusCode.OK, new { Code = -1, IsResult = false, Msg = "123456" }); } }
如果不用特性[Route] 构造函数是可以注入的
怎么解决的