有条件的依赖注入,只有当财产不为空结合 [英] Conditional dependency injection binding only when property not null

查看:179
本文介绍了有条件的依赖注入,只有当财产不为空结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有义务冒充访问底层数据源在当前用户的桌面应用程序。

It is a desktop application which is obliged to impersonate the current user when accessing the underlying data source.

我怎么能告诉Ninject不绑定依赖,直到父对象的属性不是null?


  1. 应用程序强制用户身份验证

  2. 一旦通过验证,到目前用户凭据的参考保持在 IMembershipService

  3. 内访问底层数据源责成至有认证的用户,以便commection字符串规定的凭证来冒充

其实我使用NHibernate,我需要动态创建。根据在认证时提供的用户凭据连接字符串

I am actually using NHibernate, and I need to dynamically create the connection string based on the user credentials provided upon authentication.

所以我想实现:

public class DataModule : NinjectModule {
    public override void Load() {
        Bind<ISessionFactory>().ToProvider<SessionFactoryProvider>()
            .When( // IMembershipService.CurrentUser != null );
    } 
}



由于 SessionProviderFactory 依赖于 IMembershipService.CurrentUser

我知道这可能不是设计世纪旁,我需要这样的工作方式,现在这样我就可以把我的一块潜在可交付的产品。我很高兴在事后重构。

I am aware this might not be the design of the century, beside I need it to work this way for now so that I can deliver my piece of potentially shippable product. I'll be glad to refactor afterwards.

SessionFactoryProvider

public class SessionFactoryProvider : Provider<ISessionFactory> {
    public class SessionFactoryProvider(IMembershipService service) {
        membershipService = service;
    }

    protected override ISessionFactory CreateInstance(IContext context) {
        Configuration nhconfig = new Configuration().Configure();
        nhconfig.AddAssembly(Assembly.GetExecutingAssembly());
        nhconfig.Properties["connection.connection_string"] = buildConnectiongString();
        return nhconfig.BuildSessionFactory();
    }

    private string buildConnectionString() {
        return string.Format(membershipService.GetDefaultConnectionString()
            , membershipService.CurrentUser.DatabaseInstanceName
            , membershipService.CurrentUser.Login
            , membershipService.CurrentUser.Password);
    }

    private readonly IMembershipService membershipService;
}



SessionProvider

public class SessionProvider : Provider<ISession> {
    public class SessionProvider(ISessionFactory factory) {
        sessionFactory = factory;
    }

    protected override ISession CreateInstance(IContext context) {
        return sessionFactory.OpenSession();
    }

    private readonly ISessionFactory sessionFactory;
}



事实是,我不能实例化 IMembershipService.CurrentUser 在应用程序启动。用户已经率先身份验证系统,因此 Activati​​onException

The fact is that I can't instantiate the IMembershipService.CurrentUser upon application startup. The user has first to authenticate to the system, hence the ActivationException.

错误激活的ISession

Error activating ISession

没有匹配的绑定是可用的,并且类型是不言可绑定

No matching bindings are available, and the type is not self-bindable.

激活路径:

3)依赖的ISession注射入式InquiriesRepository的构造函数的参数会议

3) Injection of dependency ISession into parameter session of constructor of type InquiriesRepository

2)的依赖注入IInquiriesRepository入式InquiriesManagementPresenter的构造函数的参数库

2) Injection of dependency IInquiriesRepository into parameter repository of constructor of type InquiriesManagementPresenter

1)请给InquiriesManagementPresenter

1) Request for InquiriesManagementPresenter

建议:

1)确保已定义的Isession绑定。

1) Ensure that you have defined a binding for ISession.

2)如果一个模块中定义的结合,确保该模块已经被加载到内核中。

2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.

3)确保你不小心创建了多个内核。

3) Ensure you have not accidentally created more than one kernel.

4)如果你使用的是构造函数的参数,确保参数名称的构造参数名称相匹配。

4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.

5)如果你使用的是自动加载模块,保证搜索路径和过滤器是正确的。

5) If you are using automatic module loading, ensure the search path and filters are correct.

那么,我该怎么做呢?

任何设计改进建议表示欢迎。但是,请记住,我需要它迫切工作。我将重构下一个送货。

Any design improvement suggestions welcome. But keep in mind that I need it to work badly. I'll refactor for the next delivery.

修改

它看起来像我也许可以使用上下文/范围依赖注入

It looks like I perhaps could use contexts/scope dependency injection.

NamedScope

和我仍然无法弄清楚如何让它在我的情况在这里工作。

And still, I cannot figure out how to make it work here in my scenario.

更新

通过我的阅读,我开始怀疑,也许语境结合会更适合我的需要比条件约束。

Through my readings, I begin to doubt that perhaps contextual binding would be more suitable for my needs than conditional binding.

有什么想法?

每个涉及有条件的结合文章是讲条件类型绑定,没有条件的国家具有约束力。

Each article which relates on conditional binding is talking about conditional type binding, not conditional state binding.

在我的情况下,就特别相信这是一个有条件的状态结合,因此有关上下文结合的想法。

In my scenario, it specifically believe it is a conditional state binding, hence the thoughts about context binding.

然后,我将有两个绑定。

Then, I would have two bindings.


  1. 的用户进行身份验证之前

  2. 的用户进行身份验证后,

所以,或许我要么必须使用延迟注入,这将解决我的问题,为的 ISessionFactory 不需要在应用程序启动一个实例。

So perhaps I either have to use lazy injection, which would resolve my problem, as an instance of the ISessionFactory isn't required on application startup.

我在这里有点损失...

I'm a bit loss here...

推荐答案

您可能能够创建一个条件约束:

You might be able to create a conditional binding:

IBindingRoot.Bind<IFoo>().To<Foo>()
    .When(request => request.ParentContext.Kernel.Get<IUserService>().AuthenticatedUser != null);



但我不推荐它; - )

But i don't recommend it ;-)

@Pacane

当条件将每一次一个请求一个IFoo的执行。将其转换为另一请求,因此有点昂贵。

The When condition will be executed every time one requests an IFoo. It translates to another request and is thus somewhat costly.

此外,这种方法只适用于情况下,存在一个父请求。如果你做了 IResolutionRoot.Get<的IFoo方式>()它会抛出一个的NullReferenceException

Also, this approach only works in case there is a parent request. In case you do a IResolutionRoot.Get<IFoo>() it will throw a NullReferenceException.

您可以解决,通过访问由句法提供的内核。但我不知道是否是怎么回事呆在那里ninject ...

You could work around that by accessing the kernel provided by the syntax. But i don't know whether it's going to stay there in future releases of ninject...

另外的未来版本中,有一个这能确保你只实例化对象树的某些部分你是完全初始化后(=>认证)的应用引导机制是一个更好的设计。至少在我看来。

Also, having an application bootstrapping mechanism which ensures that you only instanciate certain parts of the object tree after you are "fully initialized" (=> authenticated) is a better design. At least in my opinion.

这篇关于有条件的依赖注入,只有当财产不为空结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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