ASP.NET经典OWIN启动配置未调用服务

aamkag61  于 2023-03-09  发布在  .NET
关注(0)|答案(3)|浏览(128)

我正在编写一个ASP.NET经典WebAPI应用程序。我已经实现了OWIN StartUp类,并且执行了Caonfiguration方法,但是没有执行ConfigureServices方法。我知道这适用于DotNetCore。

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(ClassicWebApi.Startup))]

namespace ClassicWebApi
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //CODE IS NOT EXECUTED
        }
        public void Configuration(IAppBuilder app)
        {
            //CODE IS EXECUTED
        }

    }
}

这只是DotNetCore的一个功能,还是需要在设置中包括另一个库?

ar7v8xwq

ar7v8xwq1#

我想使用依赖项注入,特别是AddDbContext和AddScoped
内置依赖项注入仅在ASP.NET核心中可用。您将需要使用第三方IoC容器,例如-

8wigbo56

8wigbo562#

你可以在非核心项目中使用Microsoft.Extensions.DependencyInjection,你只需从Global.asaxApplication_Start方法调用ConfigureServices(IServiceCollection services)

cl25kdpy

cl25kdpy3#

如果你想在ASP.NET中使用WebAPI来使用DI,那就看看Unity吧。
Unity是向现有的遗留ASP.NET应用程序添加DI的最佳库,您可以使用它向任何应用程序添加DI,甚至是WebForms。

** Package :**

<package id="Microsoft.AspNet.WebFormsDependencyInjection.Unity" version="1.0.0" targetFramework="net472" />
<package id="Unity" version="5.2.0" targetFramework="net472" />
<package id="Unity.Abstractions" version="3.3.0" targetFramework="net472" />
<package id="Unity.Container" version="5.8.6" targetFramework="net472" />
<package id="Unity.WebAPI" version="5.3.0" targetFramework="net472" />

全局.ascx:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        UnityConfigWebForms.RegisterComponents(this, AppConfig.WebAppSettings._authType);
        UnityConfigWebAPI.RegisterComponents(AppConfig.WebAppSettings._authType);
        ...existing code...

示例类:

public static class UnityConfigWebAPI
{
    public static void RegisterComponents(WebAppSettings.AuthenticationTypes authenticationType)
    {
        var container = new UnityContainer();
        container.RegisterType<IWesTest, WesTest>(new Unity.Injection.InjectionConstructor("hi wesley, webapi"));

        //container.RegisterType<IAuthenticationService>(new InjectionFactory(c =>
        //{
        //    IAuthenticationManager mgr = HttpContext.Current.GetOwinContext().Authentication;
        //    System.Type generic = System.Type.GetType("CGI_Automation_Framework.AuthenticationEngines." + authenticationType);
        //    object ad = System.Activator.CreateInstance(generic, mgr);
        //    return ad;
        //}));

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

WebAPI类示例:

[Authorize]
public class TagController : ApiController
{
    private AppStart.IWesTest _auth;

    public TagController(AppStart.IWesTest auth)
    {
        this._auth = auth;
    }

相关问题