Unity to return new instance of service - wpf

I have come across a bit of a problem while using Unity and WPF. The scenario is I have a WPF application which follows the MVVM design pattern. A have a module called ViewKDI. Within this module I have a service called ViewKDIService, the ViewKDIService service utilises another service called UserService.
Every time I load the module ViewKDI I want Unity to return me a new instance of both the ViewKDIService and the UserService.
I have put the below in the shell bootstrapper:
Container.RegisterType<IUserService, UserService>();
In the ViewKDI module I have put the following:
Container.RegisterType<IViewKDIService, ViewKDIService>();
Each time the ViewKDI module loads the ViewKDIService constructor is called. However the UserService constructor is only called the first time, this means that I am not getting a new instance of UserService.
I require unity to give me a new instance of UserService too so that I can manage this session separately from the rest of the application.
Any ideas?
Thanks
Faisal

Unity's default behaviour is to create a new instance of each object each time one is requested, so you shouldn't be seeing this behaviour.
From what I can gather from the source code and MSDN documentation (this is a good read), you can specify a "lifetime manager" object when you register a type to tell Unity how the type should be constructed and cached. Using the TransientLifetimeManager (which essentially does no caching) will cause Unity to re-create the class each time. So try this:
Container.RegisterType<IUserService, UserService>(new TransientLifetimeManager());
... and see if it creates a new UserService each time.

Related

Context Lifetime on a WinForms app .Net6 with Dependency Injection

I am having some issues with context lifetime on my .NetCore 6 win forms application. In summary, I have a button that when clicked calls a repository which then retrieves a record from my DB and displays one value from that record in a text field. This works ok until that value changes in the database. Further clicks of the button continue to display the old value.
This is how I register my context in the winforms app
services.AddDbContext<MyContext>(b => b.UseSqlServer(connectionString));
I then register my services like this:
services.AddScoped<IMyRepo, MyRepo>();
I guess this is an issue where the form is long running and never disposes the context, hence why the result is always the same until the form is closed and reopened with a fresh context.
I am using this in my repo to force a new result each time, however is seems like a bit of a mission to do this for every request to the DB I make...
_entities.Entry(log).Reload();
Is there a cleaner way I can do this without having to do the reload?
Honestly, I wouldn't use the MS IoC AddDbContext for WinForms/WPF. There probably is a way to have it play nice with some form of lifetime scope, but I'm honestly not aware of one. I don't use it for web projects either, simply because it scopes the DbContext to the request and I like to have a bit more control over the lifetime of the DbContext in some situations. (Dealing with poisoned contexts for instance)
For web and WPF I've used a Unit of Work pattern called the DbContextScope to manage the DbContext and relationship with the Repositories. The idea being that the consumers use an injected DBContextScopeFactory to create a DbContextScope (wrapping one or more DbContext instances) and the Repositories accept an injected DbContexScopeLocator to gain access to a requested DbContextScope.
The original EF6 implementation was by Medhi El Gueddari (https://github.com/mehdime/DbContextScope || https://www.nuget.org/packages/Mehdime.Entity)
For EF Core 6: (https://www.nuget.org/packages/Zejji.DbContextScope.EFCore6)
Alternatively if the scope of a DbContext can be contained within the repository calls themselves (tracked entities don't need to be passed outside of the repository) then you could also just use an injected DbContextFactory class to provide DbContext instances on demand. The advantage of a UoW pattern like above is that you have control over the scope the DbContext instance(s) live so multiple operations can be committed together or rolled back. The DbContext instance is available between multiple repositories if needed.

DotNetCore, Prism 7, WPF - Service Not Being Created

I'm using DotnetCore, WPF and Prism 7 to make a desktop application. I have one service called DbConnectionService that doesn't seem to be created. This service is not injected into any component that is reachable through the View tree(?). Instead, it listens to the IEventAggregator and communicates with the rest of the app through that.
I'm finding that I'm not able to get it to 1. be created, and 2. if it is created it doesn't stick around (GC I assume).
Below is the code I have "shotgunning" anything that will create the DbConnectionService. All to no avail.
containerRegistry.RegisterInstance(typeof(DbConnectionService), "DbConnectionService");
containerRegistry.Register<IDbConnectionService, DbConnectionService>();
containerRegistry.RegisterSingleton(typeof(DbConnectionService));
containerRegistry.GetContainer().RegisterSingleton<DbConnectionService>();
Any help on getting this service to be created and stick around is greatly appreciated.
This service is not injected into any component
That's why it's not created. Either you inject it and rely on the container's magic to create it, or you create it yourself.
You can use the container to keep the object alive (i.e. not garbage collected) through RegisterInstance:
containerRegistry.RegisterInstance( containerRegistry.GetContainer().Resolve<DbConnectionService>() );
Note that Resolve isn't on IContainerRegistry to prevent you from doing this, because you don't want to mix registering and resolving. If you have to, make 110% sure that all dependencies of DbConnectionService are registered beforehand.

Ionic/angular provider/service - singleton - single instance?

I have read that service(angular)/provider(ionic) can be specific to components, or can be shared by components by registering it at module level. I understand that this is singleton concept that is single instance shared by all components. My question is - suppose the service/provider has code that fetches data from db based on logged in userid, then in this case, how does a single instance concept differentiate between all users using the app? Bit confused on this aspect.
As far As i know singleton means a single component/service that have content that can be shared with any other page/component/controller/...
but all that is happening in one instance of the app.
Example:
lets say in our project we have 3 pages with controllers: page1.html, ctrl1.js, page2.html, ctrl2.js, page3.html, ctrl3.js
We also have 1 service: service1.js
In service1.js we have a function called getUserName()
The concept of singleton will allow getUserName() to be called from all 3 controllers. if the service is not sigleton this means it will be related to one controller/page, so if service1.js is only related to ctrl1.js, the function getUserName() cannot be called from ctrl2.js
Important: all this is happening in one instance of the app, singleton does not mean that the service is SHARED between all running instances of the app.
That being said, if you are using your service to get data from the database based on some parameters, it is the logic you implemented that decide what data will be returned.

Reusing DbContext object created in Spring.Net across controllers and actions

What is better? Or maybe - is the following a good practice?
I use Spring.net to create an instance of DbContext and then inject it into every controller for use in actions. The object is a singleton. Sometimes I get an exception which says that the "The ObjectContext instance has been disposed.." I suspect that this might be the reason, however this is not repeatable, and so far my application is only used by me during the development.
Now, would it be better to create a DbContext in every controller class and reuse in it's actions; or maybe create the DbContext object in every action itself; or just set it in the Spring config not to be a singleton, so it is created every time it is being accessed?
It is best to inject your dbcontext using request scope. That way, the context is created on the start of a request and disposed at the end. During the request you'll have a db context available so that it can handle lazy loaded objects for you.
When you register as a singleton, the dbcontext is shared for all requests, which most of the time isn't what you want. For instance, it might be that it hold a reference to all your loaded objects, potentially loading the entire db into memory.

webservice upload and progress

Please help me with this one, I'm not sure what the correct, or best approach is. Basically I have a webservice which takes a byte stream, enabling a c# winform application to upload files to the webservice.
What I need is for the winform to upload in the background one file at a time (using basic multithread, it tries to upload them all at once). I also need to drop in there a progress bar.
How should I do it? Any ideas? I have the feeling it should be fairly straight forward. I think the application should start a new thread for the first file, wait until it's finished then dispose of the thread, create a new one for the next file and so on.
It completely depends on the technology you are using on the client side to access the web service.
If that technology allows for customization of the client proxy to the point where you can intercept transmission of messages (WCF allows this, I can't recall how much the old web services reference does), then you should be able to add your hook to see when the bytes are processed/sent.
Based on bookstorecowboy's comment about using the old "web reference" functionality in .NET, I believe that it generated proxies that derive from the SoapHttpClientProtocol class.
This being the case, I would recommend creating a custom class that derives from the SoapHttpClientProtocol class, overriding the GetWriterForMessage method. In this, you are supposed to return an XmlWriter given the Stream that is passed as a property on the SoapClientMessage parameter.
You would also create a custom class that derives from Stream which takes a Stream instance and forwards all the calls to that instance.
The only difference is that in the Write methods, you would fire an event indicating how many bytes were written.
You would then get the Stream that is exposed on the SoapClientMessage passed to the GetWriterForMessage and wrap it in your custom Stream implementation. You would also connect your event handlers here as well.
With that stream, you would create the XmlWriter and return it.
Then, for your proxies, you would use this new class that derives from SoapHttpClientProtocol and have the proxies derive from that.
As for ASP.NET 2.0 web services ("Old web services ") you could add web services extension to alter and extend it's behavior .
You could also add custom Http module .
It allows you aceess up to the stream level .
see Soap Extensions,Http Modules

Resources