Castle windsor instances are registered as singleton even though explicitly declare per web request - inversion-of-control

I am explicitly declaring my registerations as per web request lifecycle but they are still singletons.
this is a problem because my command handlers depend on an IDbConnection which is also registered per web request.
here is my registration code:
container.Register(
Classes
.FromAssemblyContaining<EcruiterCommands>()
.BasedOn(typeof (ICommandHandler<>))
.WithService.AllInterfaces()
.LifestylePerWebRequest());

I found the issue, the culprit is this line:
.BasedOn(typeof (ICommandHandler<>))
it resets the registration.

Related

ApplicationScope and REST calls

I have a project where the client (a Java stateful bean) will make a REST call to another bean (let's call it RequestBean) to perform a function and return a Response. Part of that function requires a call to a vendor's SOAP service. That service is a little slow to initialize in Java, but once initialized, then of course the calls are much faster.
I've been advised that I can move that service initialization to a separate ApplicationScoped bean (let's call it ServiceBean) so that it can initialize once and that's it. My question is about RequestBean. Should that be stateless, and how would it access the service that was initialized in ServiceBean?
I think I've figured this out. I added #Startup #Singleton to the service bean, as well as a method to pass the service reference to the request bean. This works. I'm not sure if this is really the proper way to do this, but for my immediate testing, it's sufficient.

AutoFac Module gets not disposed

I have an autofac module which implements IDisposable. The module is registerd with the containerBuilder.RegisterModule<> method and it gets resolved during container.Build. But: Dispose is not called on the module when container gets disposed.
Is this a bug, or do i miss something?
I have reproduced this with Autofac 4.6.2 and 4.8.1, didn't test other versions between.
Modules are not meant to be disposed. The link between Autofac and disposable components is fulfilled by the ILifetimeScope implementations.
A module is basically a box with a Load method, that gets executed once.
When the Load method completes, you must be done with the module.
So, if you have any resource to be kept alive and disposed afterwards, it should be kept alive (and disposed) in one of the lifetime management options.
So, you could say it's a bug, but I personally think it's just a case of a feature that is not needed for the intended use of the modules (this last phrase is just my personal opinion).
If you care to describe (maybe in another question?) what is the actual problem you're trying to solve with a disposable module, we can discuss that.

InstancePerLifeTimeScope and the life time of the objects

I am very new to Autofac dependency injection and I got these questions related to my project. I have gone through many articles but I am not getting a clear picture on some of the questions I have. Mine is a service application on .Net REST API. I am doing instance registration in App_Start module as shown below.
private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<DCLMessengerContext>()
.As<DbContext>()
.ExternallyOwned()
.InstancePerLifetimeScope();
builder.RegisterType<DbFactory>()
.As<IDbFactory>()
.ExternallyOwned()
.InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>()
.As<IUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(EntityBaseRepository<>))
.As(typeof(IEntityBaseRepository<>))
.InstancePerLifetimeScope();
builder.RegisterType<PersonServiceClient>()
.As<IPerfService>()
.InstancePerLifetimeScope();
builder.RegisterType<PagingServiceContractClient>()
.As<PagingServiceContract>()
.InstancePerLifetimeScope();
builder.RegisterType<MessageService>()
.As<IMessageService>()
.InstancePerLifetimeScope();
Container = builder.Build();
return Container;
}
My service layer is "MessageService" and there I am performing all the DB and other integration operations and getting the instances through constructor injection. These are the questions I have around this implementation.
I am using InstancePerLifeTimeScope for all my registrations. Is this is the right approach? After the life cycle of each controller request (http request), will these instances will be automatically disposed?
Do we need to manually implement any Dispose operation on any of these instances? ( I don’t have any unmanaged objects in my code)
From the service method, I need to create a fire&forget thread as well using Task.Run(). What is the best approach to supply instances to this fire&forget thread? If I use InstancePerLifeTimeScope, I can see that new thread also getting the same instances that available through the service class so I am just confused when these instances will be disposed?
When you resolve the instance per lifetime scope component, you get a
single instance per nested scope
So if you are using them in controllers. You will have one object for per request and they will be disposed. But if you resolve them in a singleton object they wil live with this object.
Is this is the right approach?
It depends what you need. If you need singleton object, it's not. If you just want to use this service in request scope use instanceperrequest it's better.
Autofac automatically calls dispose for IDisposable objects. If you
need dispose method, implement it. It's not related with autofac.
If you use another thread resolve objects in this thread. Otherwise when request disposed your objects will be disposed and your thread will be fail. Check this.

SignalR with IoC (Castle Windsor) - which lifetime for hubs?

I'm just starting out with SignalR, and have created a custom resolver for SignalR, so I can use Castle Windsor to inject dependencies via hub constructors.
I kind of assumed that I would only need to register the dependencies, but I found that it was also necessary to register the hubs themselves before my app would work. Is this expected? If so, what lifetime should I use for hubs?
By default SignalR does not register each hub with the dependency resolver. Instead it uses an IAssemblyLocator to find available assemblies that might contain SignalR Hubs. Then the IHubDescriptorProvider searches through all the available assemblies for Hubs and creates HubDescriptors.
Lastly, the IHubActivator takes a HubDescriptor and returns a newly instantiated SignalR hub (using Activator.CreateInstance) unless the Hub type associated with the HubDescriptor has been registered with the dependency resolver. In the latter case, the Hub returned from the IHubActivator will be taken directly from the dependency resolver.
Typically SignalR hubs are ephemeral meaning that they get created and destroyed for each Hub method invocation. This means that if you register your Hub with SignalR's dependency resolver, you should make sure that a new Hub instance is returned each time SignalR resolves the Hub type.
I strongly advise against registering a singleton Hub for several reasons:
Hub methods can be called in parallel. When this happens, Hub.Context can be overridden as part of the setup for another method call. This can lead to really subtle bugs. For example, with a singleton Hub, the following code might add a connection other than the caller to a group (which could obviously be a big security issue):
[Authorize(Roles="Admin")]
public async Task JoinAdminGroup()
{
await Groups.Add(Context.ConnectionId, "admin");
}
Hub.Dispose will be called after each activation. If you keep returning the same Hub, it's Dispose method will be repeatedly called. This probably won't affect you unless you implement Dispose on your Hubs, since the default Dispose implementation currently no-ops.
IIS recycles AppDomains. When this happens, you will be forced to reinstantiate your Hub anyway. Remember, SignalR will automatically reestablish active connections after your app becomes unavailable for a short period of time (as is the case with an AppDomain recycle), so you can very well have a newly instantiated Hub dealing with pre-existing connections even if you register your Hub as a Singleton with the dependency resolver.
https://github.com/SignalR/SignalR/blob/2.0.1/src/Microsoft.AspNet.SignalR.Core/DefaultDependencyResolver.cs#L79

Always resolve type in new Lifetimescope?

Is there a way to make Autofac to always resolve types in a new lifetimescope?
ie.
Container.Resolve<MyHandler>().Whatever();
Now i have to do like this:
Container.BeginLifetimeScope().Resolve<MyHandler>().Whatever();
It would be nice to be able to inject MyHandler into a class and know that MyHandler is it own scope.
Autofac does not provide a way to automatically start a new lifetime scope per component resolution.
Creating a lifetime scope is actually a process you need to control very tightly. Lifetime scopes not only help the scoping of component resolution, but also manage the deterministic disposal of components you resolve. From a memory management perspective, you shouldn't just fire up lifetime scopes without also disposing of them when you're done. Failing to dispose your created scopes can very easily cause a memory leak.
This is why you always see BeginLifetimeScope in a using statement or in a very tightly integrated scenario like ASP.NET request lifetime - so you can start a scope at a known spot and be sure to end/dispose of it. Child lifetime scopes are not automatically disposed for you once they're created - it's up to you to do that cleanup.
The Autofac wiki has some good information on lifetime scopes here.