Castle Windsor RemoveComponent False - dependency-injection

I am calling Kernel.RemoveComponent on my Windsor container and it is returning false. I know the component is present (I have verified by calling GetHandler with the same key and it returns the expected info)...so why can't I remove my component from the container? How can I troubleshoot this?
I have a bunch of authentication and authorization that happens in independent handlers and components in my WCF services before the OperationContext is established (OpertaionContext.Current is still null). During this period, I need access to the request message from the request context. I'd like to store the RequestContext instance in my container with a per-thread lifetime. Upon each new request, I need to overwrite this instance so I don't retrieve the wrong request message. Is this simply not a good task for Windsor? If I can't remove the component before re-registering each new RequestContext, then all of the RequestContexts will never get disposed, right?
Thanks!

RemoveComponent will not remove the component if there are other components depending on it. Why are you removing the component instead of not putting it in the container in the first place?

Related

Supply Context to DbMigrator

How DbMigrator works
I have code that instantiates a new DbMigrator(new Configuration())
Configuration is a custom extension of DbMigrationsConfiguration<T>, where T is DbContext
So within Configuration, there is a ContextType, which is equal to <T>.
When DbMigrator is instantiated, it attempts to create an instance of the <T> DbContext. It will either try to use an Empty Constructor on the <T> Context, or it will attempt to look for an implementation of IDbContextFactory<...> where ... is the actual type of , but not generic T.
How DbMigrator Doesn't Work
The problem is, the assembly instantiating DbMigrator has no access to the specific typed IDbContextFactory<...> that it needs to discover. Also, my DbContext has no default constructor, and I don't want it to. So I receive the exception The target context '...' is not constructible.
The thing that bothers me is, at the point I am instantiating DbMigrator, I already have an instance (or may already be within an instance) of the DbContext I am migrating. Also, I have access to a generic IDbContextFactory<T> that is not discoverable by DbMigrator's internals, but I'd be happy to provide it an instance.
The Question
So how do I tell DbMigrator to either just use my Context instance, or use an instance of a IDbContextFactory I specify? When it relies on its magic juju behind the scenes to try to discover these things (presumably using reflection/ServiceLocation) it is failing.
My Situation
Within one AppDomain, I am using n Contexts. I'd like to say one, but it's typically two, and may be more than that. So any solution that relies on a single app/web config property, or an attribute decorator, which points to a single DbConfiguration or ConnectionFactory won't work for me. Because there can only be one per AppDomain and, unless I could configure it based contextually on which Context I'm needing at the time, it is futile. So there's wiggle room there, but I dunno.
Also, there may be some juju I don't understand about EF relating to the base constructor. But I don't believe passing a DbConnection into the constructor instead of a nameOrConnectionString would work. It is still not an empty constructor. But if there's something EF does to search for constructors with that, and how to utilize it, that MIGHT work.

Iterate through all sinks and enrichers registered in Serilog

How can I iterate through all sinks (ILogEventSink objects) or enrichers (ILogEventEnricher objects), respective, registered in Serilog?
I'm using Serilog.AspNetCore.
Thanks.
So, my naive idea is:
In Emit operation I must call a third party service that require current HttpContext to be set.
It seems Emit operation runs on background thread that has not got HttpContext assigned. So in Emit operation, I want to resolve IHttpContextAccesor service and set its HttpContext property. Then I can call a third party service requiring HttpContext to be set and all will be fine.
The current httpContext instance I will get is in my custom middleware and just here is the place where I want to inject httpContext instance into the Sink instance (to its [ThreadStatic] field) to accomplish scenario described above.
Another way is recreating all Serilog (and its Sink) in a middleware on each http request and pass httpContext to its constructor as a parameter. Expensive.
Serilog doesn't support this scenario.

Getting a scoped component from a IDocumentStoreListener

I have an ASP.NET 5 app using RavenDB, and I'm trying to create an attribute that will create a "Changeset" document with the keys of all the documents that were stored by the action.
For that purpose, I created an ActionFilterAttribute instantiated via ServiceFilterAttribute, which is registered as Scoped, that sets a flag on another Scoped component, let's call it ChangesetAccessor, which holds the list of changes.
The IDocumentStore is obviously a Singleton, and the listener (IDocumentStoreListener implementation) is manually instantiated. It needs access to the current ChangesetAccessor, so I thought giving it a reference to the IServiceProvider so it can call GetService<ChangesetAccessor> as needed would be enough, but it is receiving a different instance.
How can I get the ChangesetAccessor for the "current request" from my listener?
You can actually access RequestServices off of the HttpContext to get scoped instances. It's kind of backwards, and really will depend on Microsoft.AspNet to do it, but it will work for your situation; interestingly, IHttpContextAccessor is a singleton, too, though it gives you a scoped value.
// injected:
IHttpContextAccessor httpContextAccessor;
// in your method:
httpContextAccessor.HttpContext.RequestServices.GetService<ChangesetAccessor>()

Is an instance of my controller constructor created every time I request a new page in MVC3

I have quite a few things in the constructor of my controller. Is it the case that every time I request a new page with MVC3 then the constructor executes?
A controller instance is required to serve each request. And to obtain this instance (obviously) the controller constructor is called on each request. This being said you should avoid doing many things in this constructor. There are cases for example where for some particular action on this controller you don't need all this initialization and despite this if you put it in the constructor, it will be executed. If the tasks you perform are simply instantiating some other dependencies that your controller needs, then you shouldn't worry about performance, you should worry about properly architecting your application as this job should be handled by a DI framework.
Another common gotcha is that inside the constructor you don't yet have access to the HttpContext and some properties such as Request, Response, ... might not be available in the controller constructor. They become available in the Initialize method.
All this to say that I recommend you avoid putting code (other than storing ctor argument dependencies into private variables for injecting things like services, repositories, ...) in your constructor.
The Controller base class includes the ControllerContext which is a per-request context for a controller which includes references to HttpContext for example.
Let that sink in a moment.
It's very easy to write a custom ControllerBuilder or use the new DependencyResolver to serve up a singleton controller using your favorite DI container. But what that means is your controller may hold onto state from a previous request.
In fact, one of the most common bugs when people use Castle Windsor (which uses Singleton by default I've been told) to create their controllers is they get weird behavior.
As others have pointed out, if your controller is doing a lot of work in the constructor, refactor that work into a dependency on your controller which gets passed in via your controller's contstructor. Let's call that dependency a "service".
That service can itself be a singleton (as long as it doesn't hold onto per-request state) and you can use the DependencyResolver combined with your DI container to instantiate your controllers.
It's up to the ControllerFactory to determine this; the controller factory serves up the controller instance. You could build in the ability to cache the controller, but: it would be better not to pass those references via the ctor of the controller. It would be better to cache each reference separately, and pass to the controller during construction, and let the controller get recreated everytime. If you cache the controller, it will cache other references potentially like HttpContext, which would be not the current request.
HTH.
Yes, M Jacob and this helps us making Data Access request for new DataContext in each request and it is very efficient. it is recommended to initialize a new DataContext (in your controller constructor) in each request rather than making persistent DataContext.
Internet is stateless and the server cannot really distinguish you from any other person out there (technically speaking, ignoring sessions and cookies). You are served the content and connection with you is ended. On your new request the things start from scratch. I agree with you that inability to keep an object alive is an overhead, but even bigger overhead would be if million users made a request with a different requests to the same object. Keeping million copies of the same object is next to impossible.
Regards,
Huske

Construtor/Setter Injection using IoC in HttpHandler, is it possible?

I've ran into a rather hairy problem. There is probably a simple solution to this but I can't find it!
I have a custom HttpHandler that I want to process a request, log certain info then enter the details in the database. I'm using NUnit and Castle Windsor.
So I have two interfaces; one for logging the other for data entry, which are constructor injected. I quickly found out that there is no way to call the constructor as the default parameterless constructor is always called instead.
So I thought I would use Setter injection and let Castle windsor sort it out. This actually works as when I use container.Resolve<CustomHttpHandler>(); I can check that the logger is not null. (In Application_Start in Global.asax.cs)
The problem is although Castle Windsor can create the instance the http application is not using it??? I think??
Basically the whole reason for doing it this way was to be able to test the logger and data repository code in isolation via mocking and unit testing.
Any ideas how I can go about solving this problem?
Thanks!
Not possible, at least not directly. IHttpHandler objects are instantiated by the ASP.NET runtime and it doesn't allow Windsor to get involved in its creation. You can either:
Pull dependencies, by using the container as a service locator.
Set up a base handler that creates, injects and delegates to your own handlers (see how Spring does it)
Use the container as a service locator for another service that handles the entire request (as saret explained)
What you could do is have the HttpHandler call out to another object that actually handles the request. so in your HttpHandler's ProcessRequest method you would do something like this:
public void ProcessRequest(HttpContext context)
{
var myHandlerObject = container.Resolve<HandlerObject>();
myHandlerObject.ProcessRequest(context or some state/info that is required)
}

Resources