Keep dependency injected objects for async handler in MVC3 application - c#

I am working on a MVC3 application in which I would like to handle some code blocks asynchronously. These code blocks need to perform some db operations and they need access to my DAL repositories which are initiated trough my dependency injection setup. I have set the lifetime of the repository to an "instance per http request" lifetime and I am looking for a way to extend that lifetime for the async operation.
public class AsyncController : Controller
{
private readonly ICommandBus commandBus;
private readonly IObjectRepository objectRepository;
public ActionResult DoThings()
{
DoThingsAsync();
return View();
}
private delegate void DoThingsDelegate();
private void DoThingsAsync()
{
var handler = new DoThingsDelegate(DoThingsNow);
handler.BeginInvoke(null, null);
}
private void DoThingsNow()
{
var objects = objectRepository.getAll();
foreach (Thing thing in objects)
{
thing.modifiedOn = DateTime.Now;
objectRepository.Update(thing);
}
}
}
The objectRepository is initiated for the lifetime of the request and I would like to skip the garbage collection for this object for one method in one controller only. I have tried to pass the repository as a parameter to the method and the delegate but that did not extend its lifetime.

When starting a new thread, it is wise to let the Container compose a totally new object graph for you. When you reuse dependencies that are created in the context of a HTTP request (or thread context or what have you), this can result in race conditions and other sort of failures and strange behavior.
This of course doesn’t have to be the case when you know that those dependencies are thread-safe (or created with a per-request lifetime and are not used by the request after triggering the async operation), but this is not something a consumer of these dependencies should know or should depend on, because it is the responsibility of the part of the application that wires everything together (The Composition Root). Doing this, would also make it harder to change that dependency configuration later on.
Instead, you should refactor your DoThings method into its own class and let your Controller depend on some sort of IDoThings interface. This way you can postpone the decision about handling things asynchronously until the moment you wire everything together. When reusing that logic in another type of application (Windows Service for instance), it even allows you to change the way this operation is executed asynchronously (or simply execute it synchronously).
To go even one step further, the actual DoThings business logic and the part that executes that logic asynchronously are two different concerns: two separate responsibilities. You should separate them into different classes.
Here's an example of what I advise you to do:
Define an interface:
public interface IDoThings
{
void DoThings();
}
Let your Controller depend on that interface:
public class SomeController : Controller
{
private readonly IDoThings thingsDoer;
public SomeController(IDoThings thingsDoer)
{
this.thingsDoer = thingsDoer;
}
public ActionResult DoThings()
{
this.thingsDoer.DoThings();
return View();
}
}
Define an implementation that contains the business logic:
public class DoingThings : IDoThings
{
private readonly ICommandBus commandBus;
private readonly IObjectRepository objectRepository;
public DoingThings(ICommandBus commandBus,
IObjectRepository objectRepository)
{
this.commandBus = commandBus;
this.objectRepository = objectRepository;
}
public void DoThings()
{
var objects = objectRepository.getAll();
foreach (Thing thing in objects)
{
thing.modifiedOn = DateTime.Now;
objectRepository.Update(thing);
}
}
}
Define a proxy that knows how to handle a DoingThings asynchronously:
public class DoingThingsAsync : IDoThings
{
private readonly Container container;
public DoingThingsAsync(Container container)
{
this.container = container;
}
public void DoThings()
{
Action handler = () => DoThingsNow();
handler.BeginInvoke(null, null);
}
private void DoThingsNow()
{
// Here we run in a new thread and HERE we ask
// the container for a new DoingThings instance.
// This way we will be sure that all its
// dependencies are safe to use. Never move
// dependencies from thread to thread.
IDoThings doer =
this.container.GetInstance<DoingThings>();
doer.DoThings();
}
}
Now, instead of injecting a DoingThings into the SomeController, you inject a DoingThingsAsync into the controller. The controller does not know whether the operation is executed synchronously or not, and it doesn't care. Besides that, this way you are also separating your business logic from your presentation logic, which is important for lots of good reasons.
You might want to consider using the command pattern as basis around business operations that mutate state (if you're not already using such a thing, considering the ICommandBus interface). Take for instance a look at this article. With this pattern you can more easily configure certain commands to run asynchronously or batch them to an external transactional queue, for later processing, without having to change any of the consumers of those commands.

Related

Multiple scopes in the application using Autofac

I have a question concerning lifetime scopes in Autofac.
It is allowed to create multiple scopes in different places in the application to resolve types?
In official documentation there is such a statement:
Note: generally speaking, service location is largely considered an anti-pattern That is, manually creating scopes everywhere and sprinkling use of the container through your code is not necessarily the best way to go. Using the Autofac integration libraries you usually won’t have to do what we did in the sample app above. Instead, things get resolved from a central, “top level” location in the application and manual resolution is rare. Of course, how you design your app is up to you.
What if I have several view models and I need to resolve some types in each one?
Example:
public class ClassA
{
//some code here
}
public class ClassB
{
//some code here
}
public class ClassC
{
//some code here
}
public class ViewModelA
{
public ViewModelA()
{
}
public void Method()
{
//some code here
using (var scope = Container.BeginLifetimeScope())
{
var typeC = scope.Resolve<ClassC>();
//some code here
}
}
}
public class ViewModelB
{
public ViewModelB()
{
}
public void Method()
{
//some code here
using (var scope = Container.BeginLifetimeScope())
{
var typeA = scope.Resolve<ClassA>();
var typeB = scope.Resolve<ClassB>();
//some code here
}
}
}
Assuming that all types are registered in the container - is spreading such scopes across the app is a good practice? How do you understand that?
Best regards.
TL;DR
I have a question concerning lifetime scopes in Autofac. It is allowed to create multiple scopes in different places in the application to resolve types?
Yes, it is allowed, even though it is considered not the best way to go - but definitely not the prohibited one.
What if I have several view models and I need to resolve some types in each one?
Just resolve them through constructor injection as it was suggested by #Raymond. You don't need scopes for something as simple as just resolving stuff.
Now, let's talk this through a little bit.
First of all, how do you use constructor injection? There's nothing simpler than that. Let's modify your example just a bit:
public class ClassA
{
//some code here
}
public class ClassB
{
//some code here
}
public class ClassC
{
//some code here
}
public class ViewModelA
{
private ClassC typeC;
// this is a constructor injection - yes, it's that simple.
public ViewModelA(ClassC _typeC)
{
typeC = _typeC;
}
public void Method()
{
typeC.doStuff();
}
}
public class ViewModelB
{
private ClassA typeA;
private ClassB typeB;
public ViewModelB(ClassA _typeA, ClassB _typeB)
{
typeA = _typeA;
typeB = _typeB;
}
public void Method()
{
typeA.doStuff();
typeB.doAnotherStuff();
}
}
That's it. You just specify parameters in the constructor and save those parameters somewhere in the private fields of the class - and you're good to go. Just use those objects assuming they do exist for sure. (They can be optional though, but I'll skip that for now). If autofac is unable to resolve some dependency it will throw an exception - thus if your class got created you can be absolutely sure that all the dependencies were resolved and provided to it in the constructor parameters. (Again, I'll skip some more complicated scenarios for the sake of brevity and clarity).
What does it give us? Well, now classes ViewModelA and ViewModelB know nothing about any containers or DI in general. All they know is that someone (read: "container") will somehow provide a couple of parameters of specified types (which are usually interfaces) from outside. The class itself now knows nothing about who will create its dependencies, where, when and how - it's not its concern anymore. This is the whole point of dependency injection: removing the concern of managing dependencies.
Next thing is - where are the scopes in this picture? Well... nowhere. :) That's the ideal picture: the services are completely unaware of the existence of the DI container.
But what is a lifetime scope anyways? It is a mean of controlling (surprise!) life time of the objects that are resolved from it. You typically don't need it, unless you are dealing with some edge-case scenarios.
Let's take a look at the extremely simplified example. Say, you have some job that needs to perform some kind of requests to external resources on schedule. However, the method that performs requests is actually generic: it does not know beforehand what exact type of request it is performing because it is defined by the type parameter of the method which will only be known in the runtime.
Also, let's say that you have another requirement: you need to not keep api services in the memory but rather create them only for performing the request and then discard them right away after work is done.
It could look something like the following:
abstract class SomeSpecialApi<TSomeTypeParam> { // just some common base type
public abstract string doGetStuff();
}
class SomeSpecialApi1 : SomeSpecialApi<SomeTypeParam1> where SomeTypeParam1 : TSomeTypeParam {
private HttpClient _client;
public SomeSpecialApi(HttpClient client) {
_client = client;
}
public override string doGetStuff() {
return _client.get(someUrlWeDontCareAbout).Result;
}
}
class SomeSpecialApi2 : SomeSpecialApi<SomeTypeParam2> where SomeTypeParam2 : TSomeTypeParam {
private SomeFtpClient _client;
public SomeSpecialApi(SomeFtpClient client) {
_client = client;
}
public override string doGetStuff() {
// it's just something very different from the previous class
return _client.read(someOtherPathWeDontCareAboutEither).Result;
}
}
class JobPerformer {
private ILifeTimeScope _scope;
public JobPerformer(ILifeTimeScope scope) {
_scope = scope;
}
void PerformJob<T>() {
while (true) {
using (var childScope = scope.BeginLifeTimeScope()) {
var api = childScope.Resolve<SomeSpecialApi<T>>();
var result = api.doGetStuff();
// do something with the result
} // here the childScope and everything resolved from it will be destroyed
// and that's the whole purpose of the lifetime scopes.
Thread.Sleep(1000);
}
}
}
Do you see how it works? Depending on the method's type parameter container will resolve different classes to get the job done. So, instead of creating all the dependencies and then destroying them manually all you need to do is to create your own scope, request an instance of the service you need and then destroy scope after work is done. Scope destruction takes care of destroying all the dependencies which you don't (and shouldn't) even know about. That's definitely an improvement compared to the creation of all the dependencies manually.
However, the disadvantage here is that now JobPerformer class has to know about such a thing as ILifeTimeScope. So it's in some sense similar to the ServiceLocator pattern: we have to know at least who to ask for the dependency, in other words: JobPerformer now knows something about our container. That's what we ideally want to avoid, and there are also other means to achieve it: factories; owned instances; different lifetime policies of service registrations in the container; different kinds of lifetime scopes (at least in autofac); etc.

Event dispatching library with IoC

In the past I've built a MessageDispatcher component that scans an assembly for types decorated with certain attributes and initializes an instance of each. Then, when any object is fed to the MessageDispatcher instance, every previously initialized instance which contains a method which signature contains the type of the passed object has said method triggered with the specified parameter. For example, in a scenario like:
[Listener]
public class MyListener
{
MessageDispatcher _dispatcher; //Assigned elsewhere
[MessageListener]
public async Task DoSomething(int value)
{
var otherValue = await _dispatcher.Next<string>();
Console.WriteLine($"{value} is {otherValue}.");
}
}
The following code initializes an instance of the MyListener class, calls DoSomething and prints "7 is okay.":
var listener = new MessageDispatcher(typeof (ListenerAttribute));
listener.Dispatch(7);
listener.Dispatch("okay");
I would like to know if there are any libraries out there that are dedicated to or include a service like such. It has to be able to:
Scan assemblies and initialize types based on an attribute.
Dynamically "subscribe" to certain types
"Wait" on a value to be pumped from the dispatcher (like with the Next method in my example).
(as library recommendations is not allowed per the SO rules, here is an attempt to instead answer with an implementation)
You can get that with virtually any IoC. All they need is to be able to register services using an attribute or some other conventional way.
As for the message dispatching. Just create an interface like IMessageHandler<TMessage>. Implement it on all classes that should handle messages.
Example:
public interface IMessageHandler<TMessage>
{
void Handle(TMessage msg);
}
public class SomeService : IMessageHandler<UserCreated>
{
//[.. all other methods ..]
public void Handle(UserCreated msg)
{
// ...
}
}
To publish messages you create a dispatcher. Since you use a container you do not have to make it static. Use your container inside it (service location) to dispatch the messages. Now some peeps might say oohh no, service location is anti-pattern, buhuhuhu. Well no. Not in all cases. In this case it's an implementation details in a class with the specific purpose to identify and invoke other classes.
public interface IMessageDispatcher
{
void Dispatch<TMessage>(TMessage msg);
}
// The actual implementation differs
// depending on your choice of container.
public class ContainerBasedMessageDispatcher : IMessageDispatcher
{
Container _container;
public ContainerBasedMessageDispatcher(Container container)
{
_container = container;
}
public void Dispatch<TMessage>(TMessage message)
{
using (var scope = container.BeginLifetimeScope())
{
var handlers = scope.Resolve<IEnumerable<IMessageHandler<TMessage>>();
foreach (var handler in handlers)
{
handler.Handle(message);
}
}
}
}
The code is written directly in SO. So it might not work as-is. But hopefully it's given you an idea how to achieve what you want.
Usage:
public class UserService
{
IMessageDispatcher _dispatcher;
public UserService(IMessageDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public void Create(User user)
{
//[...]
_dispatcher.Dispatch(new UserCreated(user.Id));
}
}
this do however not dynamically allow you to subscribe on what you want. If just ignoring unwanted messages is not feasible. Then this answer is not for you.

Auto Dispose Sql Connections properly

My application is using 3 layers: DAL / Service / UL.
My typical DAL class looks like this:
public class OrdersRepository : IOrdersRepository, IDisposable
{
private IDbConnection _db;
public OrdersRepository(IDbConnection db) // constructor
{
_db = db;
}
public void Dispose()
{
_db.Dispose();
}
}
My service calls the DAL class like this (injecting a database connection):
public class ordersService : IDisposable
{
IOrdersRepository _orders;
public ordersService() : this(new OrdersRepository(new Ajx.Dal.DapperConnection().getConnection()))
{
}
public ordersService(OrdersRepository ordersRepo)
{
_orders = ordersRepo;
}
public void Dispose()
{
_orders.Dispose();
}
}
And then finally within my UI layer, this is how I access my service layer:
public class OrdersController : Controller, IDisposable
{
//
// GET: /Orders/
private ordersService _orderService;
public OrdersController():this(new ordersService())
{
}
public OrdersController(ordersService o)
{
_orderService = o;
}
void IDisposable.Dispose()
{
_orderService.Dispose();
}
}
This all works good. But as you can see, I am relying on IDisposable within every layer. UI disposes service object and then service object disposes DAL object and then DAL object disposes the database connection object.
I am sure there has to be a better way of doing it. I am afraid users can forget to dispose my service object (within UI) and I will end up with many open database connections or worse. Please advise the best practice. I need a way to auto-dispose my database connections OR any other unmanaged resources (files etc).
Your question comes back to the principle of ownership:
he who has ownership of the resource, should dispose it.
Although ownership can be transferred, you should usually not do this. In your case the ownership of the IDbConnection is transferred from the ordersService to the OrdersRepository (since OrdersRepository disposes the connection). But in many cases the OrdersRepository can't know whether the connection can be disposed. It can be reused throughout the object graph. So in general, you should not dispose objects that are passed on to you through the constructor.
Another thing is that the consumer of a dependency often can't know if a dependency needs disposal, since whether or not a dependency needs to be disposed is an implementation detail. This information might not be available in the interface.
So instead, refactor your OrdersRepository to the following:
public class OrdersRepository : IOrdersRepository {
private IDbConnection _db;
public OrdersRepository(IDbConnection db) {
_db = db;
}
}
Since OrdersRepository doesn't take ownership, IDbConnection doesn't need to dispose IDbConnection and you don't need to implement IDisposable. This explicitly moves the responsibility of disposing the connection to the OrdersService. However, ordersService by itself doesn't need IDbConnection as a dependency; it just depends on IOrdersRepository. So why not move the responsibility of building up the object graph out of the OrdersService as well:
public class OrdersService : IDisposable {
private readonly IOrdersRepository _orders;
public ordersService(IOrdersRepository ordersRepo) {
_orders = ordersRepo;
}
}
Since ordersService has nothing to dispose itself, there's no need to implement IDisposable. And since it now has just a single constructor that takes the dependencies it requires, the class has become much easier to maintain.
So this moves the responsibility of creating the object graph to the OrdersController. But we should apply the same pattern to the OrdersController as well:
public class OrdersController : Controller {
private ordersService _orderService;
public OrdersController(ordersService o) {
_orderService = o;
}
}
Again, this class has become much easier to grasp and it doesn't needs to dispose anything, since it doesn't has or took ownership of any resource.
Of course we just moved and postponed our problems, since obviously we still need to create our OrdersController. But the difference is that we now moved the responsiblity of building up object graphs to a single place in the application. We call this place the Composition Root.
Dependency Injection frameworks can help you making your Composition Root maintainable, but even without a DI framework, you build your object graph quite easy in MVC by implementing a custom ControllerFactory:
public class CompositionRoot : DefaultControllerFactory {
protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType) {
if (controllerType == typeof(OrdersController)) {
var connection = new Ajx.Dal.DapperConnection().getConnection();
return new OrdersController(
new OrdersService(
new OrdersRepository(
Disposable(connection))));
}
else if (...) {
// other controller here.
}
else {
return base.GetControllerInstance(requestContext, controllerType);
}
}
public static void CleanUpRequest() }
var items = (List<IDisposable>)HttpContext.Current.Items["resources"];
if (items != null) items.ForEach(item => item.Dispose());
}
private static T Disposable<T>(T instance)
where T : IDisposable {
var items = (List<IDisposable>)HttpContext.Current.Items["resources"];
if (items == null) {
HttpContext.Current.Items["resources"] =
items = new List<IDisposable>();
}
items.Add(instance);
return instance;
}
}
You can hook your custom controller factory in the Global asax of your MVC application like this:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(
new CompositionRoot());
}
protected void Application_EndRequest(object sender, EventArgs e)
{
CompositionRoot.CleanUpRequest();
}
}
Of course, this all becomes much easier when you use a Dependency Injection framework. For instance, when you use Simple Injector (I'm the lead dev for Simple Injector), you can replace all of this with the following few lines of code:
using SimpleInjector;
using SimpleInjector.Integration.Web;
using SimpleInjector.Integration.Web.Mvc;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var container = new Container();
container.RegisterPerWebRequest<IDbConnection>(() =>
new Ajx.Dal.DapperConnection().getConnection());
container.Register<IOrdersRepository, OrdersRepository>();
container.Register<IOrdersService, OrdersService>();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
}
}
There are a few interesting things going on in the code above. First of all, the calls to Register tell Simple Injector that they need to return a certain implementation should be created when the given abstraction is requested. Next, Simple Injector allows registering types with the Web Request Lifestyle, which makes sure that the given instance is disposed when the web request ends (just as we did in the Application_EndRequest). By calling RegisterMvcControllers, Simple Injector will batch-register all Controllers for you. By supplying MVC with the SimpleInjectorDependencyResolver we allow MVC to route the creation of controllers to Simple Injector (just as we did with the controller factory).
Although this code might be a bit harder to understand at first, the use of a Dependency Injection container becomes really valuable when your application starts to grow. A DI container will help you keeping your Composition Root maintainable.
Well, if you're really paranoid about that you can use the finalizer (destructor) to automatically execute the Dispose when the object is being garbage collected. Check this link which explains basically all you need to know about IDisposable, skip to the Examples section if just want a quick sample how to do that. The finalizer(destructor) is the ~MyResource() method.
But any way, you should always encourage the consumers of your libraries to use correctly the Dispose. The automatic cleaning up, by means of garbage collector still presents flaws. You don't know when the garbage collector will do its job, so if you get lots of these classes instantiated and used, then forgotten, in a short time, you may still be in trouble.

Ninject -- how to to IOC with a class used in a Parallel.ForEach loop

I have some code that looks like below. I'm new to IoC and Ninject and don't know how to inject IOtherClass into SomeService so that the Parallel.ForEach works. My only other guess is to move the Parallel.ForEach into the DoWork method?
Thanks for any help.
public class SomeService
{
Parallel.Foreach(items, item =>
new OtherClass.DoWork(item);
}
public class OtherClass:IOtherClass
{
public void DoWork()
{...}
}
When applying dependency injection, you like to move the control of the composition of graphs of related object to a single place in the application called the Composition Root.
To remove complexity in the rest of the application, only the composition root should know which instances to create and how to create them. The composition root is the only one to know how object graphs are built and it knows (or at least when writing your DI configuration you should know) if services can safely depend on each other. Problems with thread-safety should be spotted here.
An implementation itself should not have to know whether it is safe to use the dependency; it must be able to assume that that dependency is safe to use on the thread it is running. Besides the usual transient and singleton lifestyles (where transient means that a new instance is created where singleton means that the application will only have one instance of that service) there are often other lifestyles that have a thread affinity. Take for instance the Per Web Request lifestyles.
So the general advice is to:
Let the IoC container resolve all objects for you, and
Don't move services from thread to thread.
Your SomeService implementation is correct from a thread-safety perspective, since each thread creates its own new (transient) OtherClass instance. But this starts to become problematic when OtherClass starts to have dependencies on its own. In that case you should move the creation of that object to your composition root. However, if you implement that as in the following example, you will have a problem:
public class SomeService
{
private IOtherClass other;
public SomeService(IOtherClass other)
{
this.other = other;
}
public void Operate(Items items)
{
Parallel.Foreach(items, item => this.other.DoWork(item));
}
}
The implementation is problematic, because SomeService moves a single IOtherClass instance across threads and assumes that IOtherClass is thread-safe, which is knowledge that only the composition root should know. Dispersing this knowledge throughout the application increases complexity.
When dealing with multi-threaded code, every thread should get its own object graph. This means that when starting a new thread, you should query the container/kernel again for a root object and call that object. Like this:
public class SomeService
{
private IItemProcessor processor;
public SomeService(IItemProcessor processor)
{
this.processor = processor;
}
public void Operate(Items items)
{
this.processor.Process(items);
}
}
public class ItemProcessor : IItemProcessor
{
private IKernel container;
public ItemProcessor(IKernel container)
{
this.container = container;
}
public void Process(Items items)
{
Parallel.Foreach(items, item =>
{
// request a new IOtherClass again on each thread.
var other = this.container.Get<IOtherClass>();
other.DoWork(item);
});
}
}
This deliberately extracts the mechanics about processing those items into a different class. This allows keeping the business logic in the SomeService and allows to move the ItemProcessor (which should only contain mechanics) into the composition root so the use of the Service Locator anti-pattern is prevented.
This article explains more about working with DI in multi-threaded applications. Note that it's documentation for a different framework, but the general advice is the same.
It's not obvious from your code if you are required to create new instance of OtherClass on every iteration of the loop? And I suppose that IOtherClass interface contains DoWork method?
If you can go with the same instance in every iteration then the correct way would be constructor injection.
in the constructor of the SomeService you inject IOtherClass
public class SomeService
{
private readonly IOtherClass _otherClass;
public SomeService(IOtherClass otherClass)
{
_otherClass = otherClass;
}
void YourLoopMethod()
{
Parallel.Foreach(items, item =>_otherClass.DoWork(item));
}
}
If you need new instance in every iteration of the loop, than maybe you could go with "other class factory" that is injected into SomeService
public interface IOtherClassFactory
{
IOtherClass Create();
}
public class SomeService
{
private readonly IOtherClassFactory _otherClassFactory;
public SomeService(IOtherClassFactory otherClassFactory)
{
_otherClassFactory = otherClassFactory;
}
void YourLoopMethod()
{
Parallel.Foreach(items, item =>
_otherClassFactory.Create().DoWork(item));
}
}
Here you need to implement IOtherClassFactory that knows how to create IOtherClass objects. In your implementation you can inject IKernel dependency and use it to create IOtherClass objects.
And for both scenarios you need to register Ninject kernel bindings in your composition root.
kernel.Bind<IOtherClas>().To<OtherClass>();

Add object initialization to IoC container without introducing circular dependencies

I have a class (MathController) that knows how to refresh a Math component.
That class uses a helper class for determining when to trigger the refresh, based on a time schedule.
What I'd like to do is to add the helper class to my IoC container.
Currently, the IoC creates the MathController. Since the helper class needs to receive an Action from the MathController, I don't know how to do that without getting into a circular dependencies scenario.
This is a sample I've created as an example of the scenario.
void Main()
{
var mathController = new MathController();
}
class MathController
{
private readonly StateMonitor _stateMonitor;
public MathController()
{
_stateMonitor = new StateMonitor(RefreshMath);
_stateMonitor.Monitor();
}
public void RefreshMath()
{
Debug.WriteLine("Math has been refreshed");
}
}
class StateMonitor
{
private readonly Action _refreshCommand;
public StateMonitor(Action command)
{
_refreshCommand = command;
}
public void Monitor()
{
Debug.WriteLine("Start monitoring");
Thread.Sleep(5000);
Debug.WriteLine("Something happened, we should execute the given command");
_refreshCommand();
}
}
Your IoC container may support some way to do this. For instance, NInject allows you to register a provider (basically a factory method) which could handle the initialization for you. It might help if you said which IoC container & version you're using.
Another way would be to inject a StateMonitorFactory into the MathController, instead of the StateMonitor itself. The factory would then build the StateMonitor. So the MathController might look like:
public MathController(StateMonitorFactory fact)
{
_stateMonitor = fact.CreateStateMonitor(RefreshMath);
_stateMonitor.Monitor();
}
A third option would be to have the StateMonitor have an initialization method. In that case the StateMonitor constructor would become parameterless, but you'd add another method to it with a signature like Start(Action command), and MathController would be responsible for calling that.

Categories

Resources