Different Castle interceptor instances for different dependencies - dependency-injection

I have an Castle Windsor interceptor that I want to use for two different interfaces (just call them IOne and ITwo). Similar to this post http://thatextramile.be/blog/2009/07/protecting-your-application-from-remote-problems/ I want the interceptor to be a singleton with respect to the same interface, but be a different instance for each interface. Obviously registering the interceptor as singleton causes the same instance to be reused across all instances of IOne and ITwo. I need the interceptors to behave this way because I need them to preserve state for all calls through that interface, but they need to be distinct from each other.
I've come across lots of possible ways to approach this, but since I'm not an expert on Windsor, what is the preferred way to handle this situation?

Documentation says it's recommended to use the interceptors with transient lifecycle.
Make interceptors transient
It is strongly advised that you always make your interceptors
transient. Since interceptors can intercept multiple components with
various lifestyles it's best if their own lifespan is no longer than
the component they intercept. So unless you have a very good reason
not to, always make them transient.
I suggest refactoring the shared data interaction to another interface then use that as singleton.

An alternative approach is to make the interceptor generic. Then you can specify the interceptor with the generic argument of your interface.
public class MyInterceptor<T> : IInterceptor
{
...
}
Then register like this
container.Register(Component.For<IOne>()
.ImplementedBy<OneImplementation>()
.Interceptors<MyInterceptor<IOne>>());
container.Register(Component.For<ITwo>()
.ImplementedBy<TwoImplementation>()
.Interceptors<MyInterceptor<ITwo>>());
.Net will recognize MyInterceptor<IOne> and MyInterceptor<ITwo> as separate classes, and so Windsor will create different singleton instances for them.
Of course, this only works if you're making the interceptor. If it's in some library that you don't have access to, then your out of luck with this approach.

Related

Dependency injection - trying to avoid using a service locator

Following the guidelines I read in:
https://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container
I want to try and avoid using a service locator.
But on the other hand, I don't register all the types in the startup.cs file. I don't think this is right that all these internal types are referenced in the main startup.cs
I currently have a factory class that has a collection of builder classes.
Each builder class is in charge of creating a specific object.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy.
I saw an example of how to achieve this in the link above. However the startup.cs class needs to know all these builders. I don't think this is appropriate, I'd rather have the factory class be the only one that is exposed to them. I was trying to understand if there is some kind of func/action method that I can inject from the startup.cs file into my factory class. This func/action will be in charge of creating/registering the builders and then I can activate this func/action within the class factory. I'd like this func/action to receive the interface/class/maybe name of the builder but using generics isn't working. I searched a lot and didn't find any solution so I assume this is not possible.
Seems I have 2 options:
1. Use service locator. This way only the factory class will know the builders. However if in the future, if I want to change the DI I need to "touch" the factory class (I'm contaminating the factory class). Wanted all the DI code to be located only in the startup.cs class.
2. Register the builders in the startup.cs but now the startup.cs is aware of the builders. This kinda couples the code, not really single role of responsibility
It would have been great to inject the factory class a func/action from the startup.cs that would do the registration but the factory class itself activates it.
Is this possible?
I want to try and avoid using a service locator
Great, because the Service Locator is an anti-patttern.
don't register all the types in the startup.cs file.
You should do your registrations in one single 'area' of your application: the start-up path. This area is commonly referred to as the Composition Root (the place where object graphs are composed).
I don't think this is right that all these internal types are referenced in the main startup.cs
No matter how you design it, the startup assembly is the most volatile part of the system and it always depends on all other assemblies in the application. Either directly or transitively (through another referenced assembly). The whole idea of Dependency Injection is to minimize the coupling between components and the way to do this is to centralize coupling by moving it to the Composition Root. By making types internal however, you are decentralizing object composition and that limits your flexability. For instance, it becomes harder to apply decorators or interceptors for those registered types and control them globally. Read this question and its two top voted answers for more information.
I don't register all the types
The concern of having a Composition Root that is too big is not a valid one. One could easily split out the Composition Root into multiple smaller functions or classes that all reside in the startup assembly. On top of that, if you read this, you'll understand that registering all types explicitly (a.k.a. "Explicit Register") is typically pointless. In that case you're probably better off in using DI without a Container (a.k.a. Pure DI). Composition Roots where all types are registered explicitly are not very maintainable. One of the areas a DI Container becomes powerful is through its batch-registration facilities. They use reflection to load and register a complete set of types in a few lines of code. The addition of new types won't cause your Composition Root to change giving you the highest amount of maintainability.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy
Creation of instances should never be heavy. Your injection constructors should be simple and composing object graphs should be reliable. This makes building even the biggest object graphs extremely fast. Factories should be reduced to an absolute minimum.
TLDR;
Register or compose your object graphs solely in the Composition Root.
Refrain from using the Service Locator anti-pattern; Whole applications can (and should) be built purely with Constructor Injection.
Make injection constructors simple and prevent them from doing anything else than storing their incoming dependencies.
Refrain from using factories to compose services, they are not needed in most cases.

Spring4d Event Driven Architecture or How to retrieve all instances of a given interface

I checked the sample in the Spring4d library on event driven architecture.
From what I can understand, when an event is published, the ServiceLocator will instantiate all classes that implement the IEventHandler<TEventClass> interface and ask these handlers to handle the event.
Though, is there a recommended approach to only ask already instantiated services to handle the event.
Let's say I have an arbitrary number of Controllers that are instanciated. Some of them may be the same class that is instantiated multiple times. Some of them might be unique.
I want these instantiated Controllers to listen to a TUserAdded event. These Controllers implement the IEventHandler<TUserAdded> interface. I don't want the non-instantiated Controllers to listen to the event.
In a way, I would like to get a list of all instances that implement the IEventHandler<TUserAdded> event.
Also, in the ideal case, if a Controller is registered as a Singleton
container.RegisterType<TMySingletonController>.AsSingleton;
I would like to instantiate the TMySingletonController if it is not already instantiated, then, let it handle the event.
Is there a built-in approach in Spring4d to get a list of all instances of a given interface ?
The DI container of Spring4D is a so called non tracking container which means it does not track the lifetimes of the instances it creates (except singleton ones of course).
If you want to resolve all registered services for an interface X then you can resolve TArray<X> or IEnumerable<X> but it will create new instances if they are not registered as singleton.
The sample you looked at was taken from a blog article about combining DI and event driven architecture but your problem more sounds like you need to use the observer and factory patterns. Just please don't abuse the DI container as instance repository.

Autofac Container Independence and Relationship Types

We are currently using Autofac as our chosen IoC container. All application code in our reusable assemblies must be kept as clean as possible, so we do not want any direct dependencies on Autofac in our core application. The only place where Autofac is permitted is in the composition root / bootstrappers, where components are registered and wired up. Applications rely on dependency injection to create the required object graphs.
As we are keeping our core application container agnostic, it means that we cannot use the Autofac relationship types, such as Owned, in our core application.
I would like to create a factory that returns components that implement IDisposable. As Autofac tracks disposable objects, I believe I have to use a lifetime scope to create a defined unit of work in which components will be disposed once they go out of scope.
According to the Autofac documentation, this can be achieved by taking a dependency on Func<Owned<T>>, however, as stated above, I cannot take a dependency on Owned as it is an Autofac type. At the bottom of this page, it says
The custom relationship types in Autofac don’t force you to bind your application more tightly to Autofac. They give you a programming model for container configuration that is consistent with the way you write other components (vs. having to know a lot of specific container extension points and APIs that also potentially centralise your configuration.)
For example, you can still create a custom ITaskFactory in your core model, but provide an AutofacTaskFactory implementation based on Func<Owned<T>> if that is desirable.
It is this implementation of ITaskFactory that I believe I need to implement, but I cannot find any examples.
I would be very grateful if someone could provide such an example.
Probably the best "real-world" example of this is the Autofac MVC integration mechanism. While it doesn't use Func<Owned<T>> under the covers it does show you how you might be able to implement a non-Autofac-specific mechanism to talk to Autofac under the covers.
In the MVC case, the System.Web.Mvc.IDependencyResolver is the interface and the Autofac.Integration.Mvc.AutofacDependencyResolver is the implementation. When ASP.NET MVC requests a service, it gets it from System.Web.Mvc.DependencyResolver.Current, which returns an IDependencyResolver. At app startup, that singleton gets set to the Autofac implementation.
The same principle could hold for your custom factory. While IDependencyResolver is not specific to the type it returns (it's just GetService<T>()) you could write a type-specific factory interface just as easily.

Dependency Injection - Passing dependencies all the way down

I have an MVC application with a typical architecture...
ASP.NET MVC Controller -> Person Service -> Person Repository -> Entity Framework DB Context
I am using Castle Windsor and I can see the benefit of using this along with a ControllerFactory to create controller with the right dependencies. Using this approach the Controller gets a Service injected, which in turn knows how to construct the right Repository, which in turn knows the correct DbContext to use.
The windsor config is something like this...
dicontainer = new WindsorContainer();
dicontainer.Register(Component.For<IPersonService>().ImplementedBy<PersonService>());
dicontainer.Register(
Component.For<IPersonRepository>().UsingFactoryMethod(
() => new PersonRepository(new HrContext("connectionString"))));
It this the right way to do it? I don't like the UsingFactoryMethod, but can't think of another way.
Also, what if the Repository needed a dependency (say ILogger) that was not needed by the service layer? Does this mean I have to pass the ILogger into the service layer and not use it. This seems like a poor design. I'd appreciate some pointers here. I have read loads of articles, but not found a concrete example to verify whether I am doing this right. Thanks.
I try to avoid using factory methods (as you mentioned you felt this smelled funny). To avoid this, you could create a database session object that creates a new DbContext. Then your repositories just need to get an instance of IDbSession and use its dbContext property. Then, you can also easily control the scope of the IDbSession object (don't use singleton because it's not thread safe).
I wanted to make that point so that I could make this more important point... Make your constructors take in only objects that are registered in the DI container (no options or configurations in constructors). Options and configurations should be read/writen in classes whose sole purposes it is to read/write those values. If all classes follow this model, then your DI registration becomes easy and classes can just add whatever dependencies they need in their constructors.
If you are trying to use a third party library that has options in constructors, wrap that class in your own class that has an easy to consume constructor and uses a configuration class to read the values needed to pass to the third party library. This design also introduces a layer of abstraction between your code and the third party library which can then be used to more easily swap (or stub) third party libraries when necessary.

Contextual Binding with Castle Windsor

Is it possible to get Windsor to return different implementations of a service based on a seperate parameter?
For example, if I have a User object which has a Role property, I would like to be able to hydrate this object differently according the the value of Role. I would like to use an IUserService to do this, but have the concrete implementation of IUserService determined by the IoC container.
I think that Ninject offers this functionality as "Contextual Binding" but I'm not sure if Windsor offers it without rolling my own resolution logic?
No, it is not possible (yet).
Take a look here and here.
For now take a look at HandlerProvider if it's got what you need.
If not, you may need to use ISubDependencyResolver (which is not very complicated actually).

Resources