首页 新闻 会员 周边 捐助

C# webapi使用Autofac注入失败

0
悬赏园豆:5 [已解决问题] 解决于 2017-12-18 11:48

因为使用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目录下
追随微笑的主页 追随微笑 | 菜鸟二级 | 园豆:227
提问于:2017-09-15 16:39
< >
分享
最佳答案
0

诸如不是要在构造函数中实现的吗?

收获园豆:5
MrNice | 老鸟四级 |园豆:3468 | 2017-09-15 16:51

因为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" });
        }
    }

追随微笑 | 园豆:227 (菜鸟二级) | 2017-09-15 16:54
其他回答(2)
0

如果不用特性[Route] 构造函数是可以注入的

Haozzzzzzzz | 园豆:163 (初学一级) | 2017-11-09 11:57
0

怎么解决的

tofight | 园豆:202 (菜鸟二级) | 2021-04-08 17:57
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册