且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我是怎么拿错,DI或设计,我应该怎么做呢?

更新时间:2023-12-03 19:43:22

您不需要有条件或上下文绑定的。
去,而不是最简单的方法:
方案NHibernate的配置,会话,......因为如果你没有一个运行时时机的依赖。这意味着:注入认证的用户进入NHibernate的配置建设者

You don't need conditional or contextual bindings at all. Go for the simplest approach instead: Program the nhibernate config, session,... as if you didn't have a run-time "timing" dependency. That means: Inject the authenticated user into the NHibernate Configuration builder.

然后,你只需要确保用户进行身份验证之前的对象树依赖于任何的NHibernate的部分没有实例化。这应该是很容易做到。

Then, you only need to ensure that the part of the object tree which relies on anything NHibernate is not instanciated before the user is authenticated. This should be easy enough.

使用任何种类的引导机制,首先要创建您的绑定,然后显示在登录窗口中,执行登录,成功登录后,负载(显示)应用程序的其余部分。

Using any kind of bootstrapping mechanism, first create your bindings, then show the login window, do the login, upon successful login, load (show) the rest of the application.

绑定:

IBindingRoot.Bind<Configuration>().ToProvider<ConfigurationProvider>();
IBIndingRoot.Bind<ISessionFactory>()
            .ToMethod(ctx => ctx.Kernel.Get<Configuration>().BuildSessionFactory())
            .InSingletonScope();

public class ConfigurationProvider : IProvider<Configuration> 
{
    private readonly IUserService userService;

    public ConfigurationProvider(IUserService userService)
    {
        this.userService = userService;
    }

    public object Create(IContext context)
    {
        if(this.userService.AuthenticatedUser == null)
            throw new InvalidOperationException("never ever try to use NHibernate before user is authenticated! this includes injection an ISessionFactory in any class! Postpone creationg of object tree until after authentication of user. This exception means you've produced buggy code!");

        return Fluently.Configure()
            .DataBase(MsSqlConfiguration.MsSql2008)
                .ConnectionString(connectionBuilder => connectionBuilder.Is(... create the string...)
            ....
            .BuildConfiguration();
    }
}