问题描述:

I have a windows console app (that will eventually be a windows service) that reads from queues (5 for each client). It needs to be able to read from a data store so that all of the client queues have the appropriate queue listeners set up. To make matters more complex we're using priority queues, so in some cases one listener will listen to two queues.

A previous programmer has implemented some kind of custom service locator to bind all of the assemblies together, but as the app gets bigger and more complex his code is proving to be more and more unmaintainable to the point that when we came to add a cache - it couldnt be wired up using an interceptor pattern, so the time has come to rewrite. The question is, how?

I've looked at:

Ninject dynamically bind to implementation

and

Runtime Binding: A simple task runner with ninject?

but I dont think they really match what I'm trying to achieve.

I've got something like this:

 var clientRepo = kernel.Get<IRepository<IClient>>();

foreach (var client in clientRepo.GetEntities())

{

var clientJob = new ClientJob(client, serviceUrl, kernel);

ClientJobs.Add(clientJob);

clientJob.StartJobs();

}

I want to insert code in the line above with the new in it.

Should I be trying to do this using a factory, or can it be done with code similar to the above?

网友答案:

As far as i understand i see two problems in your code:

  • You initiate your ClientJob objects using the "new" keyword by yourself, while doing that you are coupling your code and you are lossing all the point of using IOC and DI.
    If you are using ninject as your tool i suggest you use it all the way, in your case using Ninject.Extension.Factory seems like the preferred option.
    You can use this article to get strated with, read the docs and also read this example which demonstrate the extension usage.
  • The bigger problem i see is that you pass around ninject kernel to your ClientJob objects.
    This is known as "service locator" which is considered as anti pattern.
    Your appliction should reference the kernel only in it's composition root and this is the place where you create all of your objects graph. you can find much more great info about it here.

Obviously sometimes you can't create all of your object graph at app startup (as in your question) and this is the place when the factory extension becomes super handy.

Hope it helps!

相关阅读:
Top