Deploying OnePerSessionBehavior in NInject

I would like to create OnePerSessionBehavior for NInject (v1.0), and I basically got it working. The only problem that remains is how to pass fresh arguments using .WithArguments () as each new session requests something from the container. Right now I am saving the container reference as an application variable, so the module only ever loads once, so of course the binding only happens once.

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

Bind<ISomething>() .To<Something>() .Using<OnePerSessionBehavior>() .WithArgument("currentDateTime", DateTime.Now); 
+2
c # dependency-injection inversion-of-control ninject
Feb 26 '09 at 16:41
source share
2 answers

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

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

You can link it as follows:

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

Although I don't know the exact situation for you, another idea would be to create your object without worrying about entering arguments, 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); 

Will any of these ideas work?

+1
Mar 01 2018-11-11T00:
source share

You pass in the value that was evaluated during the determination of the binding. That is why you get the same value over and over again. Actually, I don’t have an easy answer from head to head, but I’ll definitely think about it, because it can be useful for testing for me.

0
Jul 14 '09 at 19:50
source share



All Articles