Ninject UOW模式,用户以后新的ConnectionString被认证 [英] Ninject UOW pattern, new ConnectionString after user is authenticated

查看:85
本文介绍了Ninject UOW模式,用户以后新的ConnectionString被认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如果任何人能在正确的方向指向我?

I wonder if any one can point me in the right direction?

我使用的是UOW库模式,已通过Ninject注入我的依赖关系。我有一个从NinjectModule,我用我的IUnitOfWork绑定到具体实施的DbContext的继承了UnitOfWorkMapp​​ing类,见下文

I am using the UOW repository pattern and have my dependencies injected via Ninject. I have a UnitOfWorkMapping class which inherits from NinjectModule, which I use to bind my IUnitOfWork to a concrete implementation of Dbcontext, see below

public class UnitOfWorkMapping : NinjectModule
{
    public override void Load()
    {
        Bind<IUnitOfWork>()
            .To<WebsiteDbContext>()
            .InRequestScope()
            .WithConstructorArgument(
                "connectionString",
                ConfigurationManager.ConnectionStrings[ConnectionStringKeys.UnauthorisedUser]
                    .ConnectionString);

        // Objects that explicitly need a DB context for the life of the request
        Bind<IUnitOfWorkInRequestScope>()
            .To<WebsiteDbContext>()
            .InRequestScope()
            .WithConstructorArgument(
                "connectionString",
                ConfigurationManager.ConnectionStrings[ConnectionStringKeys.UnauthorisedUser]
                    .ConnectionString);

        // Objects that specificall need a DB context for the life of the application
        Bind<IUnitOfWorkInApplicationScope>()
            .To<WebsiteDbContext>()
            .InSingletonScope()
            .WithConstructorArgument(
                "connectionString",
                ConfigurationManager.ConnectionStrings[ConnectionStringKeys.UnauthorisedUser]
                    .ConnectionString);
    }
}

所以,当应用程序启动并提供我的网站用户提供未经授权的用户上下文这个被调用。这方面具有连接到其具有到数据库对象受限访问数据库的用户的数据库连接。

So this gets called when the application starts and provides my site user with a context for an unauthorised user. This context has a database connection which connects to a database User which has limited access to the database objects.

一旦用户登录到网站,我想切换到另一个连接,这将给到数据库用户的上下文中使用的访问对数据库对象更广泛地获得。

Once the user has logged in to site I would like to switch to another connection which will give the context access to a Database user with wider access to the database objects.

所以由code执行到真实病情块的时候,如果(Request.IsAuthenticated)它已经使用上下文中的授权的数据库连接。

So by the time the code execution reaches the true condition block for "if (Request.IsAuthenticated)" it is already using the "authorised" database connection for the context.

    /// <summary>
    /// Handles the PostAuthenticateRequest event of the Application control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        String[] roles;
        var applicationConfiguration =
            (IApplicationConfiguration)
                DependencyResolver.Current.GetService(typeof(IApplicationConfiguration));
        var identity = HttpContext.Current.User.Identity;
        if (Request.IsAuthenticated)
        {
            var roleRepository =
                (IRoleRepository)DependencyResolver.Current.GetService(typeof(IRoleRepository));
            roles = roleRepository.GetRolesForUser(identity.Name);
        }
        else
        {
            roles = new[] { applicationConfiguration.UnknownUserRoleName };
        }
        var webIdentity = new WebIdentity(identity, roles);
        var principal = new WebsitePrincipal(webIdentity)
        {
            ApplicationConfiguration = applicationConfiguration
        };

        HttpContext.Current.User = principal;
    }

我一直没能找到的净是足够接近我的code,以适应和实施code例子。可以请任何一个建议?谢谢你在前进。

I haven't been able to find a code example on the net that is close enough to my code to adapt and implement. Please can any one advise? Thank you in advance.

如果需要,可提供完整的code的链接。

A link to the complete code can be provided if required.

解决方案:
好了,与埃里克的不懈帮助下,我们已经到了那里。我使用的解决方案是如此。

Solution: Ok, so with the tireless help of Erik we have got there. The solution I am using is as so..

public class UnitOfWorkMapping : NinjectModule
{
    public override void Load()
    {
        // Bind the IUnitOfWork for a user that is not logged in.
        Bind<IUnitOfWork>()
            .To<WebsiteDbContext>()
            .When(request => IsUserAuthenticated(request))
            .WithConstructorArgument(
                "connectionString", ConfigurationManager.ConnectionStrings[ConnectionStringKeys.MainUserConnectionString]
                    .ConnectionString);

        // Bind the IUnitOfWork for a user that is not logged in.
        Bind<IUnitOfWork>()
            .To<WebsiteDbContext>()
            .When(request => !IsUserAuthenticated(request))
            .WithConstructorArgument(
                "connectionString", ConfigurationManager.ConnectionStrings[ConnectionStringKeys.UnauthorisedUser]
                    .ConnectionString);

    }

    /// <summary>
    /// Determines if the user authenticated.
    /// </summary>
    /// <param name="request">The Ninject Activation request.</param>
    /// <returns>
    /// returns <c>true</c> if the user exists and is authenticated
    /// </returns>
    public Boolean IsUserAuthenticated(IRequest request)
    {
        return (
            (HttpContext.Current.User != null) &&
            HttpContext.Current.User.Identity.IsAuthenticated);
    }
}

我希望可以帮助别人不必花费几天试图让这个问题的底部。

I hope that helps someone not spend days trying to get to the bottom of this issue.

推荐答案

如果您要使用不同的绑定用户是否登录或退出,这是非常简单的。

If you want to use different bindings for whether a user is logged in or out, it's very simple.

Bind<IUnitOfWork>()
   .To<WebsiteDbContext>()
   .When(x => !HttpContext.Current.Request.IsAuthenticated)
   .InRequestScope()
   .WithConstructorArgument(
       "connectionString",
        ConfigurationManager.ConnectionStrings[ConnectionStringKeys.UnauthorisedUser]
           .ConnectionString);

Bind<IUnitOfWork>()
    .To<WebsiteDbContext>()
    .When(x => HttpContext.Current.Request.IsAuthenticated)
    .InRequestScope()
    .WithConstructorArgument(
        "connectionString",
        ConfigurationManager.ConnectionStrings[ConnectionStringKeys.AuthorisedUser]
           .ConnectionString);

请注意,这些都具有同样的IUnitOfWork结合,它将简单地返回基于用户是否登录或不正确的。

Note that these both have the same IUnitOfWork binding, it will simply return the correct one based on whether the user is logged in or not.

我也这样做:

Bind<IIdentity>()
    .To<WebIdentity>()
     ...

Bind<IIdentity>()
    .ToMethod(x => HttpContext.Current.User.Identity)
    .WhenInjectedInto(typeof(WebIdentity))
    ...

Bind<IPrincipal>()
    .To<WebsitePrincipal>()
    ...

然后,配置WebsitePrincipal的构造采取的IIdentity和IApplicationConfiguration参数,使WebIdentity的构造带的IIdentity和IRoleRepository作为参数(注意.WhenInjectedInto使用现有的身份)。有你的构造做的工作。

Then, configure your WebsitePrincipal's constructor to take IIdentity and IApplicationConfiguration parameters, make WebIdentity's constructor take IIdentity and IRoleRepository as parameters (note the .WhenInjectedInto uses the existing Identity). Have your constructors do the work.

然后你只需要编写以下(DI取剩下的工作):

Then you need only write the following (DI takes care of the rest):

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    HttpContext.Current.User = DependencyResolver.Current.GetService(typeof(IPrincipal));
}

这篇关于Ninject UOW模式,用户以后新的ConnectionString被认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆