How do I create an expiring singleton binding? - dependency-injection

How can I create a binding for a globally scoped singleton object whose instance expires after a certain amount of time? Once the object has expired I'd like Ninject to serve up a new instance until that instance expires, etc...
Pseudo binding to get the idea across:
Bind<Foo>().ToSelf()
.InSingletonScope()
.WithExpiration(someTimeSpan);
I'm not looking for that exact syntax, but rather a way to end up with the desired result. In essence it would be like using Ninject as a sliding app cache.
Update
The methodology that Ian suggested was correct. I just had to tweak it a little bit because using a DateTime as the context key didn't work for some reason. Here's what I ended up with:
var someTimeInFuture = DateTime.Now.AddSeconds(10);
var fooScopeObject = new object();
Func<IContext, object> scopeCall = ctx =>
{
if (someTimeInFuture < DateTime.Now)
{
someTimeInFuture = DateTime.Now.AddSeconds(10);
fooScopeObject = new object();
}
return fooScopeObject;
};
Kernel.Bind<Foo>()
.ToSelf()
.InScope(scopeCall);

You are essentially defining a timed scope. You can bind using a custom scope function and return null after a period of time.
var someTimeInFuture = DateTime.Now.AddMinutes(5);
Func<IContext,object> scopeCall = ctx => DateTime.Now > someTimeInFuture ? null : someTimeInFuture;
Kernel.Bind<Foo>().ToSelf().InScope(scopeCall);
I am not able to test this right now, but that may work.

You can use InScope(Func scope). As the documentation states:
Indicates that instances activated via the binding should be re-used as long as the object
returned by the provided callback remains alive (that is, has not been garbage collected).
You would need to implement your own custom scope which handles your scenario. A good example how to implement your own scoping is the named scope extension from
https://github.com/ninject/ninject.extensions.namedscope

Related

How to avoid changing state in F#?

I have a C# WebAPI application that uses an F# library.
The F# library has a value:
let mutable CurrentCustomer:Customer option = None
I also have:
let Customers:Map<string,Customer> option = None
Both Customers and Customer are "global variables". On start-up the C# application loads a collection of customers into this global variable Customers. Then I have a customersController that has a Post, which calls an F# function setCurrentCustomer that sets the global variable CurrentCustomer from the collection stored in Customers:
// Post in customersController:
public HttpResponseMessage Post(string identifier)
{
var _customer = FSharpLibrary.setCurrentCustomer(identifier);
// code
}
// setCurrentCustomer function:
let mutable CurrentCustomer:Customer option = None
let setCurrentCustomer() =
CurrentCustomer <- customer |> Some
CurrentCustomer
Is there any way to avoid changing state by changing CurrentCustomer?
I know I could create a function that takes a CurrentCustomer object and returns a new CurrentCustomer object, but how will the customersController know what is the current customer set to?
Is there any way of avoiding having this global mutable variable Customer?
Is there any way to avoid changing state by changing CurrentCustomer?
Yes, there are many ways to do that, but most will involve changing the design of your FSharpLibrary so that it doesn't rely on mutable state.
As a completely general answer, you could apply the State Monad, but something less involved is often sufficient. Exactly what that would be, however, is impossible to answer without knowing what you are attempting to accomplish.
how will the customersController know what is the current customer set to?
It already knows, because it's setting the current customer to the identifier argument from the Post method. That value is in scope throughout the entire method.
The question is why your FSharpLibrary has mutable state? Can't you instead implement it with pure functions?

Getting multiple references to the same method = multiple objects?

I'm new to Dart, so maybe I'm missing something here:
This works:
In my main(), I have this:
var a = _someFunction;
var b = _someFunction;
print("${a == b}"); // true. correct!
Where _someFunction is another top-level function.
This does NOT work: (at least not how I'm expecting it to)
Given this class...
class Dummy {
void start() {
var a = _onEvent;
var b = _onEvent;
print(a == b); // false. ???????
}
void _onEvent() {
}
}
Instantiating it from main() and calling its start() method results in false. Apparently a new instance of some function or closure object is created and returned whenever my code obtains a reference to _onEvent.
Is this intentional behaviour?
I would expect that obtaining multiple references to the same method of the same instance returns the same object each time. Perhaps this is intended for some reason. If so; what reason? Or is this a bug/oversight/limitation of VM perhaps?
Thanks for any insights!
Currently, the behaviour seems to be intentional, but the following defect is open since May 2012: https://code.google.com/p/dart/issues/detail?id=144
If I were to guess, I'd say that setting "var a = _onEvent;" creates a bound method, which is some sort of object that contains both the function as well as this. You are asking for bound methods to be canonicalized. However, that would require the team to create a map of them, which could lead to worries about memory leaks.
I think they made "var a = _someFunction;" work early on because they needed static functions to be constants so that they could be assigned to consts. This was so that they could write things like:
const logger = someStaticLoggingFunction;
This was in the days before statics were lazily evaluated.
In any case, I would say that comparing closures for equality is a edge case for most languages. Take all of the above with a grain of salt. It's just my best guess based on my knowledge of the system. As far as I can tell, the language spec doesn't say anything about this.
Actually, now that I've read (https://code.google.com/p/dart/issues/detail?id=144), the discussion is actually pretty good. What I wrote above roughly matches it.

How Service Container create object declared in services.yml?

Consider this code:
public function showActiveJobsAction($slug)
{
$em = $this->getDoctrine()->getEntityManager();
$category = $em->getRepository('JobeetBundle:Category')->findBySlug($slug);
if (! $category) {
throw $this->createNotFoundException('Unable to find Category entity.');
}
$jobService = $this->container->get('job_service');
$category = $jobService->populateCategoryByItsActiveJobs($category);
return $this->render('JobeetBundle:Category:jobs.html.twig', array(
'category' => $category,
));
}
job_service need JobeetBundle:Category repository to work. The repository is passed to service constructor. It's all defined in services.yml
So in this case I end up with two instance of JobeetBundle:Category repository class?
If yes how can I change my design to do it better?
Probably it's better to create code just like:
$jobService->getCatetoryWithActiveJobsByItsSlug($slug)
but I still wonder if container looks for object existance before create it?
When you get a service from the container, by default, you get always the same instance. It is also the same instance when this service is injected into another one.
So you don't have two worry, you get only one instance of the service job_service.
Here is an extract from the Symfony2 book, chapter Service Container:
As an added bonus, the Mailer service is only created once and the same instance is returned each time you ask for the service. This is almost always the behavior you'll need (it's more flexible and powerful).
Hope that helps!
In general, you wont get duplicate repositories (or services) in Symfony2 so no worries there.
This:
$jobService->getCatetoryWithActiveJobsByItsSlug($slug)
Is a better approach simply because it hides the entity manager/repository stuff from your controller. You could (in theory at least) swap out the entire Doctrine2 engine with something else and still have your controller code work.

How do I resolve an array with Unity and pass a parameter to one of the items in the array?

So here's my factory method which takes a parameter...
container.RegisterInstance<Func<IProductInstance, IQuantityModifier[]>>(
instance => container.Resolve<IQuantityModifier[]>());
Now one of the items returned by the array takes the IProductInsance parameter in its constructor. I can't figure out how to get Unity to pass the parameter in or, if I make the constructor argument a property instead, how to get Unity to set the property. No amount of dependency overrides, injection parameters etc. seem to do anything.
Of course both of these situations would be easy if I was resolving a single instance but with an array Unity doesn't seem to fully process each item.
Any ideas? What I've ended up doing is stuff like this...
container.RegisterInstance<Func<IProductInstance, IQuantityModifier[]>>(
instance =>
{
var items = container.Resolve<IQuantityModifier[]>();
QuantityModifier item = items.OfType<QuantityModifier>().SingleOrDefault();
if (item != null)
{
item.ProductInstance = instance;
}
return items;
};
I suppose ideally the item that requires the parameter would be created by a factory but then Unity would have to pass the correct value into the factory and execute it.
Cheers, Ian.
Sadly, you've hit a bug in the container. A resolve override should do the right thing here. I suspect it's the same underlying cause as this bug: http://unity.codeplex.com/workitem/8777
I'm looking in the source code for the container, the problem is in this method in ArrayResolutionStrategy:
private static object ResolveArray<T>(IBuilderContext context)
{
IUnityContainer container = context.NewBuildUp<IUnityContainer>();
List<T> results = new List<T>(container.ResolveAll<T>());
return results.ToArray();
}
The current set of overrides is part of the current build context, not the container itself, so when it grabs the container and reresolves that context is lost.
Darn, I'll have to figure out how to fix this one.

Law Of Demeter on Factory Pattern and Dependency Injection

I have a question regarding dependency injection.
say i want to create a class
call it, WebGetTask
WebGetTask would need a dependency to HttpService
bad code 1
Code:
private HttpService httpService;
...
List<WebGetTask> list = new ArrayList<WebGetTask>();
for(...)
{
list.add(new WebGetTask(httpService));
}
...
ok. i know this is bad, because httpService is injected, but its never used, except for the creation on a new WebGetTask
ok
bad code 2
Code:
private WebGetTaskFactory webGetTaskFactory;
...
List<WebGetTask> list = new ArrayList<WebGetTask>();
for(...)
{
list.add(webGetTaskFactory.newTask());
}
...
i think this is better, because we use a factory
but...
but..
from where i'm standing,
i can see that
in WebGetTaskFactory
we are still injecting a HttpService and not doing anything to it except for the sole purpose of creating a new WebGetTask
so
to recap
my question is
how do i design a factory class (WebGetTaskFactory), that creates new objects (WebGetTask) when the new objects require a dependency (HttpService) on their constructor without simply injecting and passing the dependency (HttpService) ?
or rather, is this the way to do it? if so, then it's all good, if its not, then please guide me to how to properly use DI and factory pattern.
thanks.
I'm going to assume that the code you have shown is part of a DownloadManager class, and that you inject your dependencies via the constructor. In this case, I would expect the start-up code which glues everything together to look like this:
IHttpService httpService = new HttpService();
IWebGetTaskFactory webGetTaskFactory = new WebGetTaskFactory(httpService);
IDownloadManager downloadManager = new DownloadManager(webGetTaskFactory);
The DownloadManager class only knows about the IWebGetTaskFactory interface. It does not know about IHttpService, thus satisfying the law of Demeter.
edit: After re-reading your question, it seems that you are worried that you are not "using" the HttpService in your factory, except to pass it on to a new WebGetTask. This is OK. Both WebGetTaskFactory and WebGetTask need an HttpService instance to do their job. This is not a violation of the law of Demeter.
Okay, there's nothing specifically wrong under the LoD about passing an implementation object, a "plugin" in the constructor. What's important is that the interface of the class doesn't tell you much about that implementation.
If your interface to WebGetTask depends on the exact implementation of HttpService, that violates the Law of Demeter.
The trick here is to think about the interface signature of WebGetTask. The name itself suggests that you're not quite following the Law of Demeter — or principle of least knowledge — because you're defining a class that (1) is defined as being specific for the web, and (2) is a verb instead of a noun.
Now, neither of those is necessarily wrong, but they are both "OO smells" if you will, signs that you may not be thinking object-ly enough.
So let's try "refactoring" the design. First thing, think about a GetTask that has no "web" associated with it. You can then, either at construction time or at some later time build a service object and pass it in. If it's HttpService, that's fine, but the user of your class doesn't need any information about what's under the covers.
Second thing, let's make it a noun. Call it TaskFactory — your intuition was leading you right there — with a ctor that takes an IOService, which I've just invented as being the abstract interface implemented by HttpService.
Now, you have (this is sort of Java/C++ pseudocode, don't get excited about syntax details):
class Task { ... }
class TaskFactory {
public TaskFactory(IOServer svc){...}
public Task get(){...}
}
and you use it by writing
TaskFactory fac = new TaskFactory(new HttpService());
Task tsk = fac.get();
Now, we kow the minimum about the innards of TaskFactory, the IO service, and for that matter Tasks.
There are two ways of DI: the first one is a constructor one, which is usefull when only one or two objects are injected, and a setter one (actually as many setters as needed).
If you want to use a factory method for DI than in principle its same as a constructor based one.
Example 1, for a constructor DI:
list.add( new WebGetTask( httpService ) ) ;
Example 2, for a setter DI:
WebGetTask webGetTask = new WebGetTask();
webGetTask.setHttpService(httpService);
// set other dependencies
list.add(webGetTask);
The factory method is best for when you need to use some greater logic when creating objects that may behave differently, but have the same interface, thus the LoD. Lets assume there is a DownloadManager interface implemented dynamically based on the factory parameter(s).
Example 3, creation logic encapsulated into a factory method:
public static DownloadManager createDownloadManager(HttpService httpService){
if(null!=httpService){
WebGetTask webGetTask = new WebGetTask();
webGetTask.setHttpService(httpService);
// set other dependencies
return new DownloadManagerImpl1(webGetTask);
} else {
return new DownloadManagerImpl2();
} // if-else
}

Resources