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

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.

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.

Different Castle interceptor instances for different dependencies

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.

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.

Can StructureMap re-create dependencies after they have been passed in?

I have StructureMap set-up to pass in dependencies as interfaces for handling different email protocols. The implementations however inherit from 'TcpClient'. If there is an error or disconnection, a re-connect cannot occur unless a new TcpClient has been created, therefore the dependency passed in needs to be refreshed with a new object.
How do I go about getting StructureMap to re-create the dependencies that have already been passed in?
Within the service constructor, 2 of these protocol interfaces need to be refreshed with new objects.
It would be nice if StructureMap can accomplish this without making any calls to ObjectFactory as the dependencies have already been wired up in the ServiceRegistry class.
Sounds like a custom lifestyle might do the trick. This is done by implementing the ILifecycle interface.
You could make the consuming class depend on a Func<TcpClient> instead of a TcpClient. Store the func in an instance variable, and then invoke the func whenever you want a new instance.

Multiple Requests from a Single Browser GET/POST

I'm writing my first MVC (v3) app and I think I've organized my controllers incorrectly. I'd appreciate some guidance/advice.
This all came up because I'm using Ninject for dependency injection, and wanted it to create only one instance of my concrete DataRepository for each "request". That's easy enough to do by specifying InRequestScope() in the Ninject bindings...but after doing that I still kept seeing multiple instances of my DataRepository being created.
After scratching my head for quite a while I started monitoring the BeginRequest event in the MvcApplication class (in the global.asax file). Lo and behold, what I had thought of as a single "request" -- e.g., a single postback from the browser -- was in fact yielding multiple consecutive requests. Ninject, as per the InRequestScope() declaration, dutifully created one instance of my DataRepository for each of those requests.
Unfortunately, that's not quite what I want. What I'd like is one instance of the DataRepository being created for that single browser-initiated "request". I don't see how I can do this via Ninject. I know I could specify InSingletonScope(), but while that will utilize one DataRepository instance for the "request", the instance will hang around until the webapp restarts. Which causes me all sorts of Entity Framework caching issues.
In monitoring the BeginRequest events, it looks to me like every time a different controller is called a new request is generated. In hindsight this makes sense, but it's not consistent with my app's design. For example, I have certain common action methods that various other action methods chain to (I did that rather than duplicate the same code and views in different controllers).
All of which leads me to wonder about the following: if I want to minimize the number of times my DataRepository is instantiated I have to minimize the number of times one controller chains to another controller. Which would seem to mean that my action methods need to be consolidated, and possibly duplicated in multiple controllers.
That seems... odd. If it's the right way to do things, okay, I can live with it. But I'd love to learn that I'm missing something else in the way of designing MVC apps :). Should I, for example, centralize those common functions in a service layer, and only instantiate it once per request? If that's a dumb question, apologies; I don't really understand the concept of a service layer.
Regarding your last question: It is always better to keep the controllers free of any business logic. Their main purpose is to manage its view. Any business logic belongs to a proper business layer.
Also I think it's a good design not to reuse the repository instances too intensively. Any transaction should use its own instance. See "Unit of Work". In most cases this means one instance per request. Repositories of readonly data such as a product catalog can be reused of course by declaring them in singleton scope.
See: http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

Resources