自托管web api和autofac集成。

编程入门 行业动态 更新时间:2024-10-24 17:23:14
本文介绍了自托管web api和autofac集成。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Hi 我正在托管一个web api,它在Windows服务中公开了一些REST服务。由于这是一个Windows服务,我使用HttpSelfHostServer类来托管api。有没有人对如何将autofac IoC与自托管的web api集成有任何见解。我知道在使用IIS来托管api时有一个整合nuget包但我找不到任何自托管方案。任何建议将不胜感激。 Uros

解决方案

我找到了解决问题的方法。 Actualy所需的步骤几乎与使用IIS中托管的web api设置autofac时相同。因此,要使用自托管的web api设置autofac,请按照以下步骤操作: - 下载Autofac.WebApi nuget包 - 像往常一样设置autofac构建器 - 唯一的区别是你必须将autofac指定为web api的依赖解析器。在自托管方案中无法访问GlobalConfiguration,因此您只需在HttpSelfHostConfiguration实例上使用DependencyResolver属性:

var builder = new ContainerBuilder(); // 像往常一样注册API控制器和其他类型 var container = builder.Build(); var resolver = new AutofacWebApiDependencyResolver(container); var config = new HttpSelfHostConfiguration( @ http:// localhost:9099); config.DependencyResolver = resolver; var server = new HttpSelfHostServer(config);

Hi I am hosting an web api which exposes a few REST services in a windows service. Since this is a windows service I use the HttpSelfHostServer class to host the api. Does anybody has any exprience on how to integrate an autofac IoC with self hosted web api. I know there is an integraion nuget package when using IIS to host the api but I could not find anything for self-hosted scenarios. Any advice will be appreciated. Uros

解决方案

I found the solution to my problem. Actualy the steps needed are almost the same as when setting the autofac with web api hosted in the IIS. So to set-up the autofac with the self-hosted web api follow the next steps: - download the Autofac.WebApi nuget package - set the the autofac builder as you normally would - the only difference is whan you have to assign the autofac as a dependency resolver to the web api. GlobalConfiguration is not accessible in the self-hosted scenario so you just use the DependencyResolver property on the HttpSelfHostConfiguration instance:

var builder = new ContainerBuilder(); //Register the API controllers and other types as you normally would var container = builder.Build(); var resolver = new AutofacWebApiDependencyResolver(container); var config = new HttpSelfHostConfiguration(@"localhost:9099"); config.DependencyResolver = resolver; var server = new HttpSelfHostServer(config);

更多推荐

自托管web api和autofac集成。

本文发布于:2023-11-15 04:14:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591050.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:web   api   autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!