C# 有没有办法将owin startup.cs配置为在全局asax应用程序启动之前运行?

C# 有没有办法将owin startup.cs配置为在全局asax应用程序启动之前运行?,c#,asp.net-mvc-5,owin,C#,Asp.net Mvc 5,Owin,我试图在MVC5中实现每个请求的容器和每个请求的事务模式。我已经利用全球asax为其编写了大部分代码。但是我在创建多个上下文时遇到了问题,因为owin正在创建新的DbContext类,作为其startup.cs的一部分。是否有任何方法可以在全局asax应用程序启动事件之前运行owin,以便检索在那里创建的现有上下文?我不熟悉这些模式,所以如果这个问题听起来不对,我愿意接受其他建议 public IContainer Container { get { return

我试图在MVC5中实现每个请求的容器和每个请求的事务模式。我已经利用全球asax为其编写了大部分代码。但是我在创建多个上下文时遇到了问题,因为owin正在创建新的DbContext类,作为其startup.cs的一部分。是否有任何方法可以在全局asax应用程序启动事件之前运行owin,以便检索在那里创建的现有上下文?我不熟悉这些模式,所以如果这个问题听起来不对,我愿意接受其他建议

public IContainer Container
{
    get
    {
        return (IContainer)HttpContext.Current.Items["_Container"];
    }
    set
    {
        HttpContext.Current.Items["_Container"] = value;
    }
}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ////Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());


    DependencyResolver.SetResolver(
        new StructureMapDependencyResolver(() => Container ?? IoC.Container));

    IoC.Container.Configure(cfg =>
    {
        cfg.AddRegistry(new StandardRegistry());
        cfg.AddRegistry(new ControllerRegistry());
        cfg.AddRegistry(new ActionFilterRegistry(
            () => Container ?? IoC.Container));
        cfg.AddRegistry(new MvcRegistry());
        cfg.AddRegistry(new TaskRegistry());
        cfg.AddRegistry(new ModelMetadataRegistry());
    });

    using (var container = IoC.Container.GetNestedContainer())
    {

        foreach (var task in container.GetAllInstances<IRunAtInit>())
        {
            task.Execute();
        }

        foreach (var task in container.GetAllInstances<IRunAtStartup>())
        {
            task.Execute();
        }
    }
}

public void Application_BeginRequest()
{
    Container = IoC.Container.GetNestedContainer();

    foreach (var task in Container.GetAllInstances<IRunOnEachRequest>())
    {
        task.Execute();
    }
}

public void Application_Error()
{
    foreach (var task in Container.GetAllInstances<IRunOnError>())
    {
        task.Execute();
    }
}

public void Application_EndRequest()
{
    try
    {
        foreach (var task in
            Container.GetAllInstances<IRunAfterEachRequest>())
        {
            task.Execute();
        }
    }
    finally
    {
        Container.Dispose();
        Container = null;
    }
}
公共IContainer容器
{
得到
{
return(IContainer)HttpContext.Current.Items[“_Container”];
}
设置
{
HttpContext.Current.Items[“_Container”]=值;
}
}
受保护的无效应用程序\u Start()
{
RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
////SetInitializer(新的MigrateDatabaseToLatestVersion());
DependencyResolver.SetResolver(
新的StructureMappDependencyResolver(()=>容器??IoC.Container));
Configure(cfg=>
{
AddRegistry(新的StandardRegistry());
AddRegistry(新ControllerRegistry());
AddRegistry(新的ActionFilterRegistry(
()=>容器??IoC.Container));
AddRegistry(new MvcRegistry());
AddRegistry(new TaskRegistry());
AddRegistry(newmodelMetadataRegistry());
});
使用(var container=IoC.container.GetNestedContainer())
{
foreach(container.GetAllInstances()中的var任务)
{
task.Execute();
}
foreach(container.GetAllInstances()中的var任务)
{
task.Execute();
}
}
}
公共无效应用程序_BeginRequest()
{
Container=IoC.Container.GetNestedContainer();
foreach(Container.GetAllInstances()中的var任务)
{
task.Execute();
}
}
公共无效应用程序_错误()
{
foreach(Container.GetAllInstances()中的var任务)
{
task.Execute();
}
}
公共无效应用程序_EndRequest()
{
尝试
{
foreach(中的var任务)
Container.GetAllInstances())
{
task.Execute();
}
}
最后
{
Container.Dispose();
Container=null;
}
}
结构映射类

public class StructureMapDependencyResolver : IDependencyResolver
{
    private readonly Func<IContainer> _factory;

    public StructureMapDependencyResolver(Func<IContainer> factory)
    {
        _factory = factory;
    }

    public object GetService(Type serviceType)
    {
        if (serviceType == null)
        {
            return null;
        }

        var factory = _factory();

        return serviceType.IsAbstract || serviceType.IsInterface
            ? factory.TryGetInstance(serviceType)
            : factory.GetInstance(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _factory().GetAllInstances(serviceType).Cast<object>();
    }
公共类结构MapDependencyResolver:IDependencyResolver
{
私有只读功能工厂;
公共结构MapDependencyResolver(函数工厂)
{
_工厂=工厂;
}
公共对象GetService(类型serviceType)
{
if(serviceType==null)
{
返回null;
}
变量工厂=_工厂();
返回serviceType.IsAbstract | | serviceType.IsInterface
?工厂试运行状态(服务类型)
:factory.GetInstance(serviceType);
}
公共IEnumerable GetServices(类型serviceType)
{
return _factory().GetAllInstances(serviceType).Cast();
}
Owin启动-这是在启动时全局ASAX和每个请求后执行的,但在全局ASAX代码之后执行。我希望能够将Owin上下文设置为现有上下文实例,或者首先执行此代码并获取在启动时创建的上下文

    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {

        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");

        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");

        //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        //{
        //    ClientId = "",
        //    ClientSecret = ""
        //});
    }
}
//有关配置身份验证的详细信息,请访问https://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和登录管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
//使应用程序能够使用cookie存储登录用户的信息
//以及使用cookie临时存储用户登录第三方登录提供商的信息
//配置登录cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
Provider=新CookieAuthenticationProvider
{
//允许应用程序在用户登录时验证安全戳。
//这是一种安全功能,在您更改密码或向帐户添加外部登录时使用。
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器))
}
});            
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
//允许应用程序在验证双因素身份验证过程中的第二个因素时临时存储用户信息。
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));
//使应用程序能够记住第二个登录验证因素,如电话或电子邮件。
//选中此选项后,登录过程中的第二步验证将在您登录的设备上被记住。
//这类似于登录时的RememberMe选项。
app.useTowFactoryMemberBrowserCookie(DefaultAuthenticationTypes.TwoFactoryRememberBrowserCookie);
//取消注释以下行以启用使用第三方登录提供程序登录
//app.UseMicrosoftAccountAuth
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        DependencyResolver.SetResolver(
            new StructureMapDependencyResolver(IoC.Container));

        IoC.Container.Configure(cfg =>
        {
           ...
        });

        using (var container = IoC.Container.GetNestedContainer())
        {
            foreach (var task in container.GetAllInstances<IRunAtInit>())
            {
                task.Execute();
            }

            foreach (var task in container.GetAllInstances<IRunAtStartup>())
            {
                task.Execute();
            }
        }
    }
}
public void Application_BeginRequest()
{
    foreach (var task in DependencyResolver.Current.GetServices<IRunOnEachRequest>())
    {
        task.Execute();
    }
}