We have a number of castle windsor components declared in a config file.
Some of the components somewhere deep inside might require the services of other components.
The problem is when the application is being closed and the Container is being disposed. During Dispose()/Stop() of the Startable/Disposable component (A) when it requires the services of some other component (B) ComponentNotFoundException then raised. By that time B is already removed from the container.
I've noticed that the order of components declarations in app config file is important. And reodering A and B solves the problem.
Is there a better way to influence the order in which the components are disposed?
Edited:
Following a request in comments I provide here a sample code that will throw ComponentNotFoundException:
class Program
{
static void Main()
{
IoC.Resolve<ICriticalService>().DoStuff();
IoC.Resolve<IEmailService>().SendEmail("Blah");
IoC.Clear();
}
}
internal class CriticalService : ICriticalService, IStartable
{
public void Start()
{}
public void Stop()
{
// Should throw ComponentNotFoundException, as EmailService is already disposed and removed from the container
IoC.Resolve<IEmailService>().SendEmail("Stopping");
}
public void DoStuff()
{}
}
internal class EmailService : IEmailService
{
public void SendEmail(string message)
{
Console.WriteLine(message);
}
public void Dispose()
{
Console.WriteLine("EmailService Disposed.");
GC.SuppressFinalize(this);
}
}
internal interface ICriticalService
{
void DoStuff();
}
internal interface IEmailService : IDisposable
{
void SendEmail(string message);
}
public static class IoC
{
private static readonly IWindsorContainer _container = new WindsorContainer(new XmlInterpreter());
static IoC()
{
_container.AddFacility<StartableFacility>();
// Swapping the following 2 lines resolves the problem
_container.AddComponent<ICriticalService, CriticalService>();
_container.AddComponent<IEmailService, EmailService>();
}
public static void Clear()
{
_container.Dispose();
}
public static T Resolve<T>()
{
return (T)_container[typeof(T)];
}
}
Note: See a comment in the code how swapping the order of inserting components in the container solves the problem.
By having a static IoC class you're actually using the container as a service locator, thus losing most of the benefits of dependency injection.
The problem is that without a proper injection, Windsor doesn't know about the CriticalService - IEmailService dependency, so it can't ensure the proper order of disposal.
If you refactor to make this dependency explicit, Windsor disposes the components in the correct order:
internal class CriticalService : ICriticalService, IStartable
{
private readonly IEmailService email;
public CriticalService(IEmailService email) {
this.email = email;
}
...
}
Here's how it would look like after refactoring.
I, personally, feel that any system that requires Dispose() to be called in a specific order has a flaw in the design.
Dispose() should always be safe to call. The errors should only occur if a component is used after disposal, and then ObjectDisposedException makes the most sense. In a case like this, I would rework your components so that they don't use other componetry during their Dispose() method (it really should be about cleaning each component's own, private resources). This would eliminate this issue entirely.
Related
Im trying to figure out how to dynamically instantiate class when it's first used. Something like autofac's Lazy does but without refactoring all my classes.
Is there any possiblity to do something like this:
public class MyService : IMyService {
public MyService() {
// I want it to be invoked only if SomeMethod was invoked before.
// 1. Attempt to invoke SomeMethod
// 2. call MyService.constructor
// 3. invoke MyService.SomeMethod()
}
public void SomeMethod() {
///literally any code.
}
}
It has to be done without changing existing codebase (except services registration/ autofac setup or other areas that could be changed without much effort), and all services look's like that:
public class Service : IService {
public Service(AnotherService service){
///...
}
}
My initial idea was to create Proxy class and then while registering services wrap it with that proxy.
It could look something like this:
public class Proxy<T>
{
private T _target;
private bool instantiated = false;
private void Instantiate()
{
Console.WriteLine("Creating instance");
_target = Activator.CreateInstance<T>();
}
public void xxx() - this method should be called every time any wrapped type method get's called.
{
if (instantiated == false)
{
Instantiate();
instantiated = true;
}
/// proceed with invocation. (im not sure how to do this via reflection).
}
}
The main issue with this idea is that above proxy class should be created at runtime via reflection and it has to mimic wrapping class behaviour.
I'd appreciate any advice on how to approach this problem.
All i want to lazy create dependencies in autofac container (currently if dependency A is requiring dependency B then B is instantiated, i want change this to instantiate B only if any method from A calls B.method).
Thanks!
What you're looking for is the Proxy pattern. You can create a lazy proxy as follows:
public class LazyMyServiceProxy : IMyService
{
private readonly Lazy<MyService> lazy;
public LazyMyServiceProxy(Lazy<MyService> lazy) => this.lazy = lazy;
public void SomeMethod() => this.lazy.SomeMethod();
}
You can use this proxy using the following Autofac registrations.
builder.RegisterType<MyService>();
builder.RegisterType<LazyMyServiceProxy>().As<IMyService>();
I am applying the Service Locator pattern as described in Game Programming Patterns, and am wondering about a possible generic implementation. The following code does work, but I am confused about using a class that is both generic and static.
The idea of the following C# code is to provide a "global" service to other parts of the application, exposing only an interface rather than the full implementation. Each service registered using this method will only have one instance in the application, but I want to be able to easily swap in/out different implementations of the provided interfaces.
My question is: when I use the following class to provide different services throughout my application, how does C# know that I am referring to different services of different types? Intuitively, I would almost think that the static variable, _service, would be overridden with each new service.
public static class ServiceLocator<T>
{
static T _service;
public static T GetService()
{
return _service;
}
public static void Provide(T service)
{
_service = service;
}
}
Here's some usage:
// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);
// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();
// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);
// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();
C# creates a separate closed type for every combination of generic parameters for open type.
Since every combination of generic parameters creates a separate class, calling a static constructor and creating own members for each of them.
You can think of them like of different classes.
public static class GenericCounter<T>
{
public static int Count { get; set; } = 0;
}
GenericCounter<int>.Count++;
GenericCounter<int>.Count++;
GenericCounter<string>.Count++;
Console.WriteLine(GenericCounter<double>.Count); // 0
Console.WriteLine(GenericCounter<int>.Count); // 2
Console.WriteLine(GenericCounter<string>.Count); // 1
This code outputs:
0
2
1
For example, in your case, behavior will be the same as if you created two separate classes:
public static class ServiceLocatorOfIMap
{
static IMap _service;
public static IMap GetService()
{
return _service;
}
public static void Provide(IMap service)
{
_service = service;
}
}
public static class ServiceLocatorOfICamera
{
static ICamera _service;
public static ICamera GetService()
{
return _service;
}
public static void Provide(ICamera service)
{
_service = service;
}
}
and used it like this:
// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocatorForICamera.Provide(_camera);
// Elsewhere, usage:
ICamera camera = ServiceLocatorForICamera.GetService();
// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocatorForIMap.Provide(CurrentMap);
// Elsewhere, using this different service:
IMap map = ServiceLocatorForIMap.GetService();
In general, it is similar to what C# does when it meets static generic classes.
I use this for cases where I can't use dependency injection all the way down (like WebForms) but I want to write testable classes that are resolved by a DI container.
The usage looks like
using(var resolved = new ResolvedService<ISomeService>())
{
resolved.Service.DoSomething();
}
The good:
You can use a DI container to resolve and release resources
It's disposable, and disposing causes the container to release the resources
It keeps the container and service registrations out of sight
The bad:
It requires a static class, but that's also in the composition root so it's not too bad.
As written it depends directly on Windsor. It's easy to replace that with any other container. Maybe one day I'll break this apart so that ServiceLocator isn't coupled to any particular container. But for now it's trivial to change that.
Using this means that while the larger component (like an .aspx page) isn't testable, what I inject into it is testable. It just gave me a crazy thought - I could write orchestrators for WebForms pages so that they're mostly testable. But hopefully I'll never need to do that.
internal class ServiceLocator
{
private static IWindsorContainer _container;
internal static void Initialize(IWindsorContainer container)
{
_container = container;
}
internal static TService Resolve<TService>(string key = null)
{
if (_container == null)
{
throw new InvalidOperationException(
"ServiceLocator must be initialized with a container by calling Initialize(container).");
}
try
{
return string.IsNullOrEmpty(key)
? _container.Resolve<TService>()
: _container.Resolve<TService>(key);
}
catch (ComponentNotFoundException ex)
{
throw new InvalidOperationException(string.Format("No component for {0} has been registered.", typeof(TService).FullName), ex);
}
}
internal static void Release(object resolved)
{
_container.Release(resolved);
}
}
public class ResolvedService<TService> : IDisposable
{
private bool _disposed;
private readonly TService _resolvedInstance;
public TService Service
{
get { return _resolvedInstance; }
}
public ResolvedService(string key = null)
{
_resolvedInstance = ServiceLocator.Resolve<TService>(key);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~ResolvedService()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
ServiceLocator.Release(_resolvedInstance);
_disposed = true;
}
}
This question is more of a "how do I do it?", rather than a "what am I doing wrong?". I have a class which is called QueryProcessor that processes queries (think CQRS). That object is injected into my presenters. The QueryProcessor needs to use the kernel to resolve bindings. Injecting the kernel in, either directly or via a factory, is easy. Doing so without causing a memory leak is the trick.
I have verified using a memory profiler that none of my QueryProcessor objects are being garbage collected. The class looks like this:
public sealed class QueryProcessor : IQueryProcessor, IDisposable
{
private readonly IKernelFactory _container;
private bool _disposed;
public QueryProcessor(IKernelFactory container)
{
_container = container;
}
//[DebuggerStepThrough]
public TResult Process<TResult>(IQuery<TResult> query)
{
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = _container.RetrieveKernel().Get(handlerType);
return handler.Handle((dynamic)query);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
// dispose of stuff here
_disposed = true;
}
}
}
public interface IKernelFactory
{
IKernel RetrieveKernel();
}
My composition root is reasonably straightforward. I am using the factory extension of Ninject.
public void OnLoad(IKernel kernel)
{
// Auto-Register all the validators which are stored in the Service assembly.
AssemblyScanner.FindValidatorsInAssembly(_serviceAssembly).ForEach(
result => kernel.Bind(result.InterfaceType, result.ValidatorType)
);
ManualRegistrations(kernel);
kernel.Bind<IKernelFactory>().ToFactory();
AutoRegisterType(kernel, typeof(IQueryHandler<,>));
AutoRegisterType(kernel, typeof(ICommandHandler<>));
}
As mentioned, the injection is working, but it is leaving a memory leak. How am I supposed to get the Ninject kernel resolving stuff in my QueryProcessor without causing the leak?
Thanks
Update - New Problem
I tried to solve this problem by creating a new kernel with a new module, separate from the main kernel of the Composition Root. These sub-kernels would be created and disposed up, with their lifetimes being tied to that of the QueryProcessors. I hooked it up like this in the main module:
kernel.Bind<IQueryProcessor>().ToMethod(ctx => new QueryProcessor(new StandardKernel(new ProcessorModule(_serviceAssembly)))).InTransientScope();
It works fine before the kernel is disposed of for the first time. But after that, I get the following error message:
Error loading Ninject component ICache
No such component has been registered in the kernel's component container.
Suggestions:
1) If you have created a custom subclass for KernelBase, ensure that you have properly
implemented the AddComponents() method.
2) Ensure that you have not removed the component from the container via a call to RemoveAll().
3) Ensure you have not accidentally created more than one kernel.
Damned if I do, damned if I don't ...
Since your application, not the DI container, is creating the instance it is also responsible for disposing the instance. This scenario can be handled by using the Register, Resolve, and Release pattern.
If you inject the kernel, then you have effectively implemented the service locator anti-pattern. This means your application is explicitly dependent on your DI framework.
Rather than injecting the kernel, you should use an abstract factory as mentioned in the post DI Friendly Framework to handle both creating and releasing the handler instances.
public interface IHandlerFactory
{
dynamic Create(Type handlerType);
void Release(dynamic handler);
}
public interface HandlerFactory
{
private readonly Func<Type, dynamic> handlerMethod;
public HandlerFactory(Func<Type, dynamic> handlerMethod)
{
if (handlerMethod == null)
throw new ArgumentNullException("handlerMethod");
this.handlerMethod = handlerMethod;
}
public dynamic Create(Type handlerType)
{
return handlerMethod(handlerType);
}
public void Release(dynamic handler)
{
IDisposable disposable = handler as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
Usage
public sealed class QueryProcessor : IQueryProcessor
{
private readonly IHandlerFactory handlerFactory;
public QueryProcessor(IHandlerFactory handlerFactory)
{
if (handlerFactory == null)
throw new ArgumentNullException("handlerFactory");
this.handlerFactory = handlerFactory;
}
//[DebuggerStepThrough]
public TResult Process<TResult>(IQuery<TResult> query)
{
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = this.handlerFactory.Create(handlerType);
try
{
return handler.Handle((dynamic)query);
}
finally
{
this.handlerFactory.Release(handler);
}
}
}
Note that if you use this approach, you are not requiring every handler to implement IDisposable, nor does your QueryProcessor unnecessarily need to implement IDisposable.
In your composition root, you just need to implement the handler method and register it as a parameter to your factory.
Func<Type, dynamic> handlerMethod = type => (dynamic)kernel.Resolve(type);
kernel.Bind<IHandlerFactory>().To<HandlerFactory>()
.WithConstructorArgument("handlerMethod", handlerMethod);
Of course, if you are processing your handlers asynchronously you have to keep the instance alive until the end of the request rather than disposing it as soon as the handler.Handle() method returns. If that is the case, I suggest you analyze the source code for WebApi to work out what pattern is used to do that when dealing with the System.Web.Http.ApiController.
I have two .NET parties who needs be bound by a contract. Now, party1 and party2 need to be able call some methods on each other (most of it is calls and reporting result back). I have duplex contract in mind, but the parties are not using WCF.
Is there a design pattern for this?
Edit
The parties are part of the same application. I create the application (party1) and someone else creates a dll (party2) that I load dynamically. Now, both of us should be able to call methods on each other. So, I am out to create an interface contract between us. The intent is to know whether there is a know pattern to do that?
A common solution is to use some kind of pub/sub pattern. By doing so you can avoid circular dependencies.
Basically you create some kind of class which are used to subscribe on events (and publish them).
So both your classes does something like this (but with different events):
public class ClassA : IEventHandler<UserCreated>
{
IEventManager _eventManager
public ClassA(IEventManager manager)
{
// I subscribe on this event (which is published by the other class)
manager.Subscribe<UserCreated>(this);
_eventManager = manager;
}
public void Handle(UserCreated theEvent)
{
//gets invoked when the event is published by the other class
}
private void SomeInternalMethod()
{
//some business logic
//and I publish this event
_eventManager.Publish(new EmailSent(someFields));
}
}
The event manager (simplified and not thread safe):
public class EventManager
{
List<Subscriber> _subscribers = new List<Subscriber>();
public void Subscribe<T>(IEventHandler<T> subscriber)
{
_subscribers.Add(new Subscriber{ EventType = typeof(T), Subscriber = subscriber});
}
public void Publish<T>(T theEvent)
{
foreach (var wrapper in subscribers.Where(x => x == typeof(theEvent)))
{
((IEventHandler<T>)wrapper.Subscriber).Handle(theEvent);
}
}
}
The small wrapper:
public class Subscriber
{
public Type EventType;
public object Subscriber;
}
Voila. the two classes are now loosely coupled from each other (while still being able to communicate with each other)
If you use an inversion of control container it get's easier since you can simplify the event manager and just use the container (service location) to resolve all subscribers:
public class EventManager
{
IYourContainer _container;
public EventManager(IYourContainer container)
{
_container = container;
}
public void Publish<T>(T theEvent)
{
foreach (var subscriber in _container.ResolveAll<IEventHandler<T>>())
{
subscriber.Handle(theEvent);
}
}
}
I think you can use next logic:
Class1: Interface1 , Class2:Interface2,
class Manager{
public Manager(Interface1 managedPart1,Interface2 managedPart2){
... some logic for connect to interfaces
}
}
This way reminds me pattern Bridge, but this is very subjective
Suppose that your code is properly designed for DI and IOC through constructor injection of any dependencies. Then whether an IOC container or DI-by-hand is used or not at the composition root doesn't matter much for this problem. I think.
Anyway, I find myself over and over again in a mental struggle with how I should best deal with scope-based services, like transactions or other obviously transient operations. There are constraints that I want to abide to:
Don't let dependency interfaces be IDisposable - it's a leaky abstraction that only the actual implementing type (and the fiddler sitting at the composition root) should care about.
Don't use static service locator types deep down the graph to resolve a dependency - only inject and resolve through the constructor.
Don't pass the IOC container, if any, as a dependency down the graph.
To be able to use using, we need IDisposable, but since a dependency interface shouldn't be IDisposable, how do you get around it to get scoped behavior?
In cases like this I would inject a service factory that creates those scoped services and let the service interface derive from IDisposable. This way the factory would be responsible to create the appropriate service instances and the only point that decides which service implementation to return. You would not need to inject the scoped service anywhere.
public interface ITransaction : IDisposable
{
}
public interface ITransactionFactory
{
ITransaction CreateTransaction();
}
public class Foo
{
private readonly ITransactionFactory transactionFactory;
public Foo(ITransactionFactory transactionFactory)
{
this.transactionFactory = transactionFactory;
}
public void DoSomethingWithinTransaction()
{
using(ITransaction transaction = this.transactionFactory.CreateTransaction())
{
DoSomething();
}
}
}
Most IoC containers today have substantial built-in support for units of work of this nature.
In Autofac, the mechanism that best fits your requirements is the Owned<T> relationship type. You can see it in action (and get some more material) via this article.
Hope this helps,
Nick
Roll your own "garbage collector" maybe? Something that periodically checks IsComplete and/or an LastAccessed attribute of a Dictionary<Transaction> and wastes the "old" ones. It's "a walking memory leak" but either you clean-up explicitly (like through IDisposable) or you workout how to clean-up automatically.
There may be an AOP solution to kicking-off the "gc"... a commit/rollback sounds like a good place to cut... and maybe you won't even need a GC at all... just cleanup the transaction on the way back-up the callstack from commit or rollback.
Good luck with it. I'll be interested to see what solutions (and ideas) other people come-up with.
Cheers. Keith.
I guess another alternative you could use is to wrap your instances with a disposable type, that way it could automatically handle the disposal of the type regardless of whether the type is actually disposable. E.g, I could define something like:
public class DisposableWrapper<T> : IDisposable
{
private readonly T _instance;
private readonly IDisposable _disposable;
public DisposableWrapper(T instance)
{
_instance = instance;
_disposable = instance as IDisposable;
}
public void Dispose()
{
if (_disposable != null)
_disposable.Dispose();
}
public static implicit operator T(DisposableWrapper<T> disposableWrapper)
{
return disposableWrapper._instance;
}
}
(Hopefully with a bit more error handling!)
Given that I know at the point of disposal whether the type is disposable, I can call it accordingly. I can also provide an implicit operator to cast back to the inner type from it. With the above, and a nifty extension method:
public static class DisposableExtensions
{
public static DisposableWrapper<T> Wrap<T>(this T instance)
{
return new DisposableWrapper<T>(instance);
}
}
Let's imagine that I have a service I am injecting into a type, it could be:
public interface IUserService
{
IUser GetUser();
}
I could potentially do something like:
public HomeController(IUserService service)
{
using (var disposable = service.Wrap())
{
var user = service.GetUser();
// I can even grab it again, implicitly.
IUserService service2 = disposable;
}
}
Now regardless of whether that concrete implementation of IUserService is disposable or not, I can still safely work on the assumption that it doesn't matter.
Another quick console example:
class Program
{
static void Main(string[] args)
{
using (var instance = new ClassA().Wrap())
{
ClassA instanceA = instance;
}
using (var instance = new ClassB().Wrap())
{
ClassB instanceB = instance;
}
Console.ReadKey();
}
}
public class ClassA
{
}
public class ClassB : IDisposable
{
public void Dispose()
{
Console.Write("Disposed");
}
}