Autofac - does lifetime scope use root scope instance if it exists? - autofac

This is likely a noob question.
Suppose I need to resolve some interface say IFunctional in web request processing which is registered as instance per lifetime scope in autofac configuration. But before I do it, I have already resolved IService which is registered as single instance and also has dependency on IFunctional. Therefore IService has already been resolved in root scope and IFunctional has already been resolved in root scope as well. Now trying to resolve IFunctional in say, web request processing, will it:
create new instance of IFunctional in "web request scope"
look for an instance of IFunctional in tree of scopes and find one in root scope and use that one?
To me the first option makes more sense, but I would rather be sure. Thanks!

In your stuation:
IService (singleton) has IFunctional(per lifetime). So this IFunctional object will live with IService. But other classes will not use this IFunctional. In short: This IFunctional will be just used by IService.
When request starts, also new request lifetime scope starts. So when you tried to resolve/get IFunctional object in this scope, it checks are there any IFunctional object in my scope ?. If there is not, it creates new one. Otherwise it uses IFunctional which is in this scope, not in other scopes even in root one (Because IFunctional is not singleton).
Therefore, The first option will take place.

Related

How inject dependency in custom TelemetryInitializer?

We are using Autofac 4 for DI and I started experimenting with AI a short while ago. Now I created a IdentityTelemetryInitializer class which needs and IIdentityProvider to be able to get the ID of the current authorized user and set it add it to the context. I cannot find a way in which to inject dependencies into a TelemetryInitializer. If I define a contructor that takes an IIdentityProvider, the custom initializer is skipped altogether.
Any ideas are welcome. I was thinking of having the user ID also set as the Thread Principal so that we can access it this way, but I was hoping I could use DI for this?
You cannot inject dependencies using a constructor as the initializer initialized internally using the default (empty) constructor. When you explicitly defined a new ctor you've actually 'removed' the default one, thus the initializer was skipped altogether, as you've mentioned.
Therefore, the only way is to resolve the dependencies during the 'Initialize' method, after registering them on application startup.
ctx.RegisterType<MyService>().As<IService>().AsSelf(); // on application startup
ctx.Resolve<IService>(); // during initializer 'Initialize' method
You might look at the question I asked here
How to have "Request" events with authenticated user id ?
because I had managed to have the TelemetryInitializer working, passing user id via the HttpContext as suggested by #yonisha.
Off course it's not as lean as what you try to achieve.
The Telemetry Initializer is called each time you instanciate a Telemetry class, so really depending of how you manage them. Btw I am looking for good advice/best pratice on that : for the moment I have one private instance on each Controller that need to track something, but that does not smell good due to lifetime of Controller.

How do I register a binding with both delayed instantiation and as a singleton

I am new to scaldi. I have a class being used in my cloud environment configuration where I want two things to happen.
bind [EnvironmentInfo] to new EnvironmentInfo initWith(_.init())
First, I want it to be a singleton. It retrieves the runtime information (Google AppEngine in this case) and it should do this once on instantiation. It seems like initWith is a good choice.
Next, I want instantiation to be delayed until first request. Following the execution path it is being instantiated well before the first call.
If I can get delayed instantiation, then initWith should move to the class constructor.
My answer ended up being simple. I abstracted the singleton "state" and accessed it as a 'lazy val ...'.

What does kernel.Bind<SomeType>().ToSelf() do?

I understand the following Ninject registration:
kernel.Bind<ISomeType>().To<SomeTypeImplementation>();
which tells Ninect to fulfill requests for ISomeType by using SomeTypeImplementation.
However I'm not sure what the following is good for.
kernel.Bind<ApplicationDbContext>().ToSelf();
Which was suggested that I use from this question:
What ninject binding should I use?
It makes ApplicationDbContext "self-bindable". If you don't have an interface to bind to, you can bind to the class itself. It's more useful if you add a scope to the call such as:
kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope();
Any time it sees the ApplicationDbContext that needs to be injected, it will reuse the same object as long as it is in the same HTTP request.
The default scope is transient, which means that any time a class requests ApplicationDbContext it will create a new instance of it. This can be problematic if you have two classes that both need to use the context in the same transaction. That is why you will often see it done with InRequestScope().
By self-binding a type, you enable that type for the following:
Lifecycle Management by the container.
Enable the container to inject dependencies into other types that depend on the self-bound type, and inject dependencies of this type into its instances likewise.
Very useful if you just have one single implementation or you don't need to use abstractions for some reason.

Unity IoC Explicitly ask container for new instance

It appears that Unity IoC defaults to creating a new instance of an object when it resolves a type. But my question is there someway to be explicit and tell my container that whenever I have it resolve an object type to give me a new instance of said type?
IE i want to be explicit and force the container to make sure theInstance is a new instance each time it resolves type:MyNewObject (or all types for that matter)
MyNewObject theInstance = container.Resolve<MyNewObject>();
Yes it is easily configurable by a TransientLifetimeManager
When you register a class should have something like
container.Register<IMyNewObject, MyMewObject>(new TransientLifetimeManager());
//or
container.Register<MyMewObject>(new TransientLifetimeManager())
If you're applying IoC principles properly, your class declares its dependencies and then the container handles the lifecycles of them. For example, you want to grab an HttpRequest object and the container handles providing the current thread-local one, or whatever.
Your code shouldn't really have to care about the life-cycle of its dependencies, as it should never be responsible for clearing up after them or what-have-you (all of that should be encapsulated in the dependency itself, and invoked by the container when it is shut down).
However, if you do need to care in your code about whether you get a singleton instance or a per-injected instance of the same type, I like to be explicit about it by using the type system itself, just as the Guice container for Java does with its Provider pattern. I've created a Guice-style IProvider<T> interface that I use to do this, and I just wire it up with a simple static factory method for them like so:
Provider.Of<Foo>(() => { /* Code to return a Foo goes here */})

instance of class held by composition container in mef

I understand that a MEF CompositionContainer creates and keeps instances of classes. I don't know under what circumstances a CompositionContainer has a class instance in its bowels.
Can anybody list operations performed on the CompositionContainer or methods of the CompositionContainer class that cause the CompositionContainer to store an instance of a class within the CompositionContainer.
Is it possible to view class instances held within a CompositionContainer in the debugger or any other fashion?
The CompositionContainer will keep references to all shared parts for the lifetime of the CompositionContainer. (The default CreationPolicy is Any for both imports and exports, which means by default all parts will be shared unless otherwise specified.)
References to NonShared parts will be kept if the part implements IDisposable. The reference will be released when the root export that was pulled from the container is released (if that export was from a NonShared part). Exports can be released either by calling CompositionContainer.ReleaseExport, or ExportLifetimeContext.Dispose for exports created with an ExportFactory.
I don't think there's any simple way to view what's held by the CompositionContainer. The source code is available so you could theoretically dive into it and figure out exactly where it's stored.
In regards to your second question (#2 above) ...
Using the QuickWatch Window (Shift + F9) or a regular Watch window, copy the following in there:
((System.ComponentModel.Composition.Hosting.CompositionContainer)(this.Container))._catalogExportProvider._activatedParts
The line above assumes that the object you are stopped on has a "this.Container" property, which is the CompositionContainer of the scope you are referring to.
From there, you'll get an array of ActivatedParts. You then navigate the dictionary of Parts. Find the Part Definition you want to find the instance of, and expand its "Non-Public Members". There you will find the CachedInstance, and this will be the instance of your "Shared" exported part that's been created.
I think Parts that are exported NonShared and not IDisposable aren't cached or held onto at all. At least that's the behavior I've seen.