在NInject实施OnePerSessionBehavior [英] Implementing OnePerSessionBehavior in NInject

查看:189
本文介绍了在NInject实施OnePerSessionBehavior的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个NInject OnePerSessionBehavior(V1.0)和我大部分得到它的工作。剩下的唯一问题是,如何在新的论据使用.WithArguments(),因为每个新的会话请求从容器中的东西通过。现在,我要保持容器的引用作为一个应用程序变量,因此该模块只会被加载一次所以当然的约束力只发生一次。



有关例如,'东西'为每个新的会话,但在传递给所有会话构造函数参数如下返回单个实例是一样的日期时间。

 绑定< ISomething>()
。为<东西>()
。采用< OnePerSessionBehavior>()
.WithArgument(currentDateTime,DateTime.Now);


解决方案

你能传递一个LAMDA作为你的论点?举例来说,如果你有一个类是这样的:

 公共类的东西:ISomething 
{
公什么(动作<&日期时间GT;初始化)
{
变种现在=初始化();
}
}

您可以按如下方式绑定:



 绑定< ISomething>()
。为<东西>()
。采用< OnePerSessionBehavior>()
.WithArgument(初始化,()=> {返回DateTime.Now;});



虽然我不知道你确切的情况,另一个想法是,无需担心创建的对象参数注入,和然后的设置你的属性。

  kernel.Bind< ISomething>()到< ;东西方式>()使用与所述; OnePerSessionBehavior>(); 
VAR mySomething = kernel.Get<&东西GT;();
mySomething.DateCreated = DateTime.Now;



  mySomething.Initialize(DateTime.Now); 



要么这些思想工作?


I'd like to create a OnePerSessionBehavior for NInject (v1.0) and I've mostly got it working. The only issue that remains is how to pass in fresh arguments using .WithArguments() as each new session asks for something from the container. Right now I'm keeping a reference to the container as an application variable and therefore the module only ever gets loaded one time so of course the binding only occurs once.

For example, the following returns individual instances of 'Something' for each new session, but the constructor argument passed in to all sessions is the same DateTime.

Bind<ISomething>()
    .To<Something>()
    .Using<OnePerSessionBehavior>()
    .WithArgument("currentDateTime", DateTime.Now);

解决方案

Can you pass a lamda as your argument? For instance, if you have a class like this:

public class Something : ISomething
{
    public Something(Action<DateTime> initializer)
    {
        var now = initializer();
    }
}

You can bind it as follows:

Bind<ISomething>()
    .To<Something>()
    .Using<OnePerSessionBehavior>()
    .WithArgument("initializer", () => { return DateTime.Now; });

Though I don't know you exact situation, another idea would be to create your object without worrying about argument injection, and then set your properties:

kernel.Bind<ISomething>().To<Something>().Using<OnePerSessionBehavior>();    
var mySomething = kernel.Get<Something>();
mySomething.DateCreated = DateTime.Now;

or:

mySomething.Initialize(DateTime.Now);

Would either of those ideas work?

这篇关于在NInject实施OnePerSessionBehavior的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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