【问题标题】:OWIN Startup ClassOWIN 创业班
【发布时间】:2014-09-15 19:12:31
【问题描述】:

谁能告诉我 OWIN 启动类的确切作用。基本上我在找什么:

  • 它的目的是什么
  • 何时调用,仅调用一次或每次请求
  • 这是配置我的依赖注入库的好地方吗?

【问题讨论】:

  • 感谢我已经完成的指针。你能告诉我这是否是配置 DI 的好地方,如果不是,我应该在哪里配置它?
  • 我没有得到的是 DI 是什么?
  • 依赖注入(Autofac,Unity)
  • 您为此使用了哪种技术?即 .Net:MVC 或 elz

标签: dependency-injection owin


【解决方案1】:

Owin 被设计为可插拔设计。您可以从配置中更改/替换一组服务。例如在以下配置中,我有

  • 启用 webapi
  • 启用信号器
  • 为 Signalr 启用基于属性的路由
  • 配置的默认依赖解析器
  • 用自定义记录器替换了记录服务

这样,你就可以配置完整的配置了。它只会在启动时调用一次。您可以在此处设置/使用依赖解析器并对其进行配置,但这主要取决于您的整体设计。

public class OwinStartup
{
    //initialize owin startup class and do other stuff
    public void Configuration(IAppBuilder app)
    {
        app.UseWelcomePage("/");
        //var container = new UnityContainer();

        HttpConfiguration httpConfiguration = new HttpConfiguration();
        httpConfiguration.Routes.MapHttpRoute(
            name: "MyDefaultApi",
            routeTemplate: "api/v2/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );

        //Maps the attribute based routing
        httpConfiguration.MapHttpAttributeRoutes();

        //Set the unity container as the default dependency resolver
        httpConfiguration.DependencyResolver = new UnityWebApiDependencyResolver(new UnityContainer());

        //replace (or add) the exception logger service to custom Logging service
        httpConfiguration.Services.Replace(typeof(IExceptionLogger), new ExLogger());
        app.UseWebApi(httpConfiguration);

        //Add Signalr Layer
        app.MapSignalR(new HubConfiguration
        {
            EnableJSONP = true,
            EnableDetailedErrors = true
        });
    }

    public class ExLogger : ExceptionLogger
    {
        public override void Log(ExceptionLoggerContext context)
        {
            base.Log(context);
            //do something
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2018-01-29
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多