I am using simpleInjector 2.8.0.0 I would like to construct just one instance of a dbContext during a lifetime scope.
(My dependency chain has 2 dependencies on IDatabaseContext/DbContext)
I have a scope decorator which implements the lifetime scope (The scope decorator is being injected into a SignalRHub):
using (ServiceHost.Container.BeginLifetimeScope())
{
var commandHandler = ServiceHost.Container.GetInstance<ICommandHandler<TCommand>>();
//constructs 2 DbContexts.
commandHandler.Handle(command);
}
I have a lifetime scope registration for the IDatabaseContext:
container.RegisterLifetimeScope<IDatabaseContext, DatabaseContext>();
However, I can see (from a Guid) that I am creating 2 instances of the IDatabaseContext/DbContext within the scope.
Are you sure this is the same scope? Either you are nesting scopes, or you what you see is two actual request being handled. In the debugger, you might be able to view request information, for instance by inspecting the HttpContext.Current.Request.Url property.
Related
I was reading a book about Learning ASP.NET Core API when I run to a part saying:
We create a private read-only field _repository that will be assigned
the injected MockCommandAPIRepo object in our constructor and used
throughout the rest of our code.
Here is some text I thought you'd better have:
Then there are some explanations related to the picture above:
Add the new using statement to reference ICommandAPIRepo.
We create a private read-only field _repository that will be assigned the injected MockCommandAPIRepo object in our constructor
and used throughout the rest of our code.
The Class constructor will be called when we want to make use of our Controller.
At the point when the constructor is called, the DI system will spring into action and inject the required dependency when we ask for
an instance of ICommandAPIRepo. This is Constructor Dependency
Injection.
We assign the injected dependency (in this case MockCommandAPIRepo) to our private field (see point 1).
And that’s pretty much it! We can then use _repository to make use of our
concrete implementation class, in this case MockCommandAPIRepo. As
I’ve stated earlier, we’ll reuse this pattern multiple times through
the rest of the tutorial; you’ll also see it everywhere in code in
other projects – take note.
Now, According to the highlighted part above in number 2, I got a little confused!
I've heard of "to be assigned by some value" before, but here, it is saying that:
that will be assigned the injected MockCommandAPIRepo object in our constructor
and as you see, there is no "by" added before the injected MockCommandAPIRepo object....
So, I have a question now. What does it mean by the highlighted part above in number 2?
Does it mean the same when we add "by" in the sentence? or not?
This is about dependency injection in Asp.Net Core. After we register service to the IOC Container, How to use it in our controller? We can inject them in controller via Constructor Injection. Once we register a service, the IoC container automatically performs constructor injection if a service type is included as a parameter in a constructor. In your question, An IoC container will automatically pass an instance of ICommandAPIRepo(MockCommandAPIRepo) to the constructor of CommandsController. Now we can use MockCommandAPIRepo in the constructor. But it can only be used in constructor, How can we use it in other method in CommandsController? Here we use:
private readonly ICommandAPIRepo _repository;
to create a global variable in CommandsController, Then in constructor, We use:
_repository = repository
assign the value of repository to _repository. Now _repository and repository has the same value, Because _repository is a global variable, So We can use _repository in other method in CommandsController. The whole process of dependency injection is done.
In a .Net Core 2.2 application, I need a version of a service as transient and a version as scoped.
For a "regular" service, I could create two different interfaces, register one as transient and one as scoped, but if both need a DbContext, it would mean I'd need to create two DbContext (yes, one can just be a wrapper) and register both, but it feels improper.
I'm using dotnet Core's default Dependency Injection framework, which I'm not that familiar with. In UnityIoC, I could easily have done that using named registrations:
//Note: Pseudo-code
void Register(IUnityContainer container)
{
container.RegisterType<IMyInterface, MyClass>(
"Transient",
new TransientLifetimeManager()
new InjectionConstructor(
new ResolvedParameter<MyDbContext>("Transient")));
container.RegisterType<IMyInterface, MyClass>(
"PerResolve",
new "PerResolve", new PerResolvedLifetimeManager()()
new InjectionConstructor(
new ResolvedParameter<MyDbContext>(PerResolve)));
container.RegisterType<MyDbContext>("Transient", new TransientLifetimeManager());
container.RegisterType<MyDbContext, MyClass>("PerResolve", new PerResolvedLifetimeManager());
}
Bonus points: Using the IServiceProvider, how do I ask for the transient resolution vs the scoped resolution?
The simplest way to implement this is with two interfaces as shown in the following example:
interface IMyScopedInterface
{
void Foo();
}
interface IMyTransientInterface
{
void Foo();
}
class MyClass : IMyTransientInterface, IMyScopedInterface
{
public MyClass(MyDbContext dbContext)
{
}
public void Foo()
{
}
}
and then register your class using the following:
services.AddTransient<IMyTransientInterface, MyClass>();
services.AddScoped<IMyScopedInterface, MyClass>();
You don't need to do anything special with your DbContext in order to support this. Let's walk through how the DI system would resolve these services to see if it can clarify why that's the case.
To start, the DI system tries to obtain an instance of IMyScopedInterface (typically because the DI system is trying to instantiate some other service whose constructor takes an IMyScopedInterface parameter).
Because IMyScopedInterface has been registered with a scoped lifetime, the DI system first looks within it's collection of services that have already been instantiated for the current scope to see if it has already created an IMyScopedInterface. That search comes up empty handed, so the DI system then moves on to create a new instance of MyClass.
To do that, it examines MyClass's constructor and determines that it needs a MyDbContext, so it recurses back through this same flow in order to obtain a MyDbContext.
The DI system constructs an instance of MyClass supplying the obtained MyDbContext, and then caches this MyClass object as part of the current scope so that subsequent requests for IMyScopedInterface within the same scope can receive the shared object.
The same basic flow holds true for IMyTransientInterface except that the DI system doesn't bother looking for a previously instantiated instance of the object, and after constructing the new MyClass instance it doesn't cache it at all.
What should hopefully be clear from this flow is that it doesn't really matter what the lifetime of MyDbContext is. If it's registered as transient, then every new instance of MyClass will get it's own unique instance of MyDbContext. If MyDbContext's lifetime is scoped (which is the default behavior in Entity Framework), then all instances of MyClass created within a given scope will share a single instance of MyDbContext regardless of whether the MyClass instances were instantiated for IMyScopedInterface or IMyTransientInterface.
I am building an WPF application using the MVVM Light Toolkit and specifically SimpleIoc.
I have a parent viewmodel that dynamically creates child viewmodels. When doing this I am using "standard" dependency injection to pass a IConfigService as a parameter to the constructor. I want the IConfigService to be a unique instance for each child viewmodel. So I try this:
IConfigService service = SimpleIoc.Default.GetInstance<IConfigService>(key);
ChildViewModel vm = new ChildViewModel(service);
Where key is a unique identifier for each child viewmodel. According to the documentation of MVVM Light and SimpleIoc this GetInstance method:
...provides a way to get an instance of a given type corresponding to a given key. If no instance had been instantiated with this key before, a new instance will be created.
There is also a remark that the class must have been registered before, else it returns null. In my case it has been, in ViewModelLocator:
var configService = new ConfigService();
SimpleIoc.Default.Register<IConfigService>(() => configService);
However, the GetInstance call returns the same instance every time.
What am I doing wrong here?
You registered an already instantiated object.
SimpleIoc does not create its own instances with this overload. It always returns configService. Either you need to perform the instantiation within the lambda, because you are using a factory overload, or you can do this more easily by just passing the ConfigService type. SimpleIoc will take care of the instantiation itself.
For ASP.NET Web API, I've been working on my own implementation of IHttpControllerActivator and am left wondering when (or why?) to use the HttpRequestMessage extension method "RegisterForDispose".
I see examples like this, and I can see the relevance in it, since IHttpController doesn't inherit IDisposable, and an implementation of IHttpController doesn't guarantee its own dispose logic.
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = (IHttpController) _kernel.Get(controllerType);
request.RegisterForDispose( new Release(()=> _kernel.Release(controller)));
return controller;
}
But then I see something like this and begin to wonder:
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
if (controllerType == typeof(RootController))
{
var disposableQuery = new DisposableStatusQuery();
request.RegisterForDispose(disposableQuery);
return new RootController(disposableQuery);
}
return null;
}
In this instance RootController isn't registered for disposal here, presumably because its an ApiController or MVC Controller? - And thus will dispose itself.
The instance of DisposableStatusQuery is registered for disposal since it's a disposable object, but why couldn't the controller dispose of the instance itself? RootController has knowledge of disposableQuery (or rather, it's interface or abstract base), so would know it's disposable.
When would I actually need to use HttpRequestMessage.RegisterForDispose?
One scenario I've found it useful for: for a custom ActionFilter.
Because the Attribute is cached/re-used, items within the Attribute shouldn't rely on the controller to be disposed of (to my understanding - and probably with caveats)... so in order to create a custom attribute which isn't tied to a particular controller type/implementation, you can use this technique to clean up your stuff. In my case, it's for an ambient DbContextScope attribute.
RegisterForDispose it's a hook that will be called when the request is disposed. This is often used along with "some" of the dependency injection containers.
For instance, some containers (like Castle.Windsor) by default will track all dependencies that they resolve. This is according to Windsor ReleasePolicy LifecycledComponentsReleasePolicy which states that it will keep track of all components that were created. In other words your garbage collector will not be able to cleanup if your container still tracks your component. Which will result into memory leaks.
So for example when you define your own IHttpControllerActivator to use it with a dependency injection container it is in order to resolve the concrete controller and all its dependencies. At the end of the request you need to release all the created dependencies by the container otherwise you will end with a big memory leak. You have this opportunity doing it with RegisterForDispose
I use RegisterForDispose with the DI container's. Based on Blog post I have implemented to dispose the container(Nested Container) after each request so that it clears all the objects which i has created.
One may want to hook code around the life cycle of a request that (1) has little to do with controllers and (2) does not subclass the request type.
I would imagine the idiomatic form of such code takes the shape of extension methods on HttpRequestMessage, for example. If the code allocates disposable resources, it would need to hook the disposal code to something. I'm not too familiar with the various extension points of the ASP.NET pipeline, but I suppose hooking code just to dispose of resources at the end of the request processing stage was common enough to justify a dedicated registration mechanism for disposable resources (as opposed to more generally subscribing code to be executed).
Since you're asking, I found a nice example scenario in this sample. Here, an Entity Framework context is set as a property of the request, and must be disposed of properly. While this property is intended to be used by controllers, they're not specific to any controller or controller super-class, so in my opinion this is a very sensible design choice. If you're curious why, this is because these requests are "OData batch requests" and controller actions will be invoked multiple times over the lifetime of each request (once per "operation"). Certain operations are grouped into atomic "changesets" that must be wrapped in transactions at a higher-level than controllers (a dedicated mechanism is used: an ODataBatchHandler, so that the controllers themselves are oblivious to this). Hence, controllers alone are not enough, as one cannot have them dispose of the context themselves in this scenario.
Hope this helps.
Autofac newbie here, but I like what I see so far. I'm trying to take advantage of request-lifetime of my resolved objects and I'm having trouble confirming that a dispose is actually happening after a request is done.
I have a disposable object that I get at the start of a page request and dispose at the end. I'm using autofac to get an instance of the object now and I wanted to see if autofac would do the disposing for me.
i've instrumented the Dispose() method on the object in question, and i can see it 'fire' when my page does the lifetime management. I see no evidence when I don't dispose myself but let autofac do it.
I'm using these instructions to get thigns configured, including the web.config and global.asax changes. I am able to instantiate the object just fine but I can't tell if it's really being disposed. Is there another step?
Whether you dispose the object manually within the page or let the Autofac module do it, there will be a difference in when your object is disposed in respect to the request lifecycle. The Autofac ContainerDisposalModule will not dispose the Request container, and with it your object, until the HttpApplication.EndRequest is fired, which is at the very end of the request lifecycle.
Depending on how you are tracing the call to your objects Dispose method, there could be a possibility that you don't see the output. How are you instrumenting your Dispose method?
Repeat of answer from your re-post:
Most of the time this happens (in any
IoC container) you'll find that one
component along a chain of
dependencies is a singleton.
E.g.
A -> B -> C
If A is 'factory', B is 'singleton'
and C is 'factory', then resolving A
will get a reference to the singleton
B, which will always reference the
same C.
In order for a new C to get created
every time you resolve A, B must also
be 'factory'.
I figured it out!
I was asking the WRONG container for the object instance - I was asking the application-container for the object and not the request-container.
D'oh!
Dispose is nothing more than an interface that allows you to define a "Dispose" method. The most common use for requiring a disposable class is if there are resources in that class that should be freed explicitly (such as a windows resource handle). For the most part the IDisposable interface is not required, as the garbage collector is extremely powerful and will do a much better job at managing memory. However, obviously there are plenty of cases where handles must be freed immediately, which brings me on to the next point, implementation of IDisposable.
What NOT to do:
var myClass = MyDisposableClass();
// do stuff with myClass
myClass.Dispose();
Proper usage:
using (var myClass = MyDisposableClass())
{
// do stuff with myClass
}
The compiler will effectively build the same as the following:
MyDisposableClass myClass = MyDisposableClass();
try
{
// do stuff with myClass
}
finally
{
myClass.Dispose();
}
The important distinction being that no matter what happens, you know your Dispose will get called. In addition, you can tie a destructor (which if exists, is called by the Garbage Collector) which you can then tie in to call your Dispose method; but if you need to do this for whatever reason be sure to not free the same resource twice (set your pointers to null after releasing).