How to implement DI using DbContext in Windows Form - winforms

I have a class running in a winforms app which uses EF Code First. The DbContext is created via DI through the class constructor. All works well.
The problem is the data being referenced is also being modified via a web site, using the same DI pattern with EF Code First, and the data changes are not being reflected in the context instance in the winforms app.
I can solve this by recreating the DbContext object in winforms every time I access it, but seems to be more of a service location pattern to me?
Is there a true DI technique to achieve this?
Or should I remove the context from the DI and use service location?

Were you not happy with the answer to your other question (http://stackoverflow.com/questions/7657643/how-to-force-ef-code-first-to-query-the-database) which suggested using Detach, AsNoTracking or Overwrite Changes?
1) Maybe you could pass an interface that has the ability to create a DbContext, instead of the context itself.
using(var context = _contextFactory.Create()) {
var entity = from table in context.Blah...;
}
The Create method could either create the concrete class itself (defeating the DI pattern a bit), or use service location to have one created for it. Not that nice, but it's better than embedding service location calls everywhere and still means you're controlling the lifecycle yourself.
2) Change the WinForm to read from a webservice run by the website, effectively similar to disabling caching.
3) Deep in the heart of MVC (well not really that deep) it is referencing the DI container directly and using it as a service locator to pass as arguments for newly created objects. Technically you could do something similar in WinForms, but it would need you to split your application up into little chunks (controllers) that don't have a very long lifetime. Maybe it's worth looking at some MVC/MVP frameworks for WinForms, although I found myself cringing at most I saw after a quick google.

The problem is the data being referenced is also being modified via a web site, using the same DI pattern with EF Code First, and the data changes are not being reflected in the context instance in the winforms app.
This is a problem with your expectations.
If your web service and window forms app are in separate processes, they won't share in-memory data.
If you want to sync their in-memory data, simply re-query in one context after committing to the database in the other. This is the same as trying to share data between different SQL connections.
I can solve this by recreating the DbContext object in winforms every time I access it, but seems to be more of a service location pattern to me?
If you want to recreate the DbContext repeatedly, you could use an abstract factory to allow manual re-creation of the object, yet allow you to inject the specific implementation into the factory.
This is not (necessarily) the Service Locator pattern, and you would have to ensure that you manually dispose your DbContext instances. I'd give you some example code, but different DI containers have totally different ways of accomplishing a factory pattern.
Or you could simply make sure that you commit your data on the web service side, and re-query the data on the WinForms app side.

Related

Best Design Pattern for a WPF MVVM application

I´m developping a project using WPF + MVVM.
The program needs to load objects (cases) from a repository and allow the user to edit it.
The main functionalities are:
CRUD of cases
Know which cases have been loaded
Know which case is currently selected
Currently, the version 0.1 uses a singleton class Session (in namespace model) to store a list from all cases loaded.
There is also a "Case Management" service that perform several operations in the Session singleton:
Load a case from the repository and store it in Session
Remove cases
Verify if a case is valid
Select a case for editing
I´m new to WPF, and I would like to know if there is a design pattern that is suitable for this situation. I´m afraid that I´m not going to the right direction.
I dont know if I have provided all information needed, but I´m willing to answer any question as fast as I can.
Your design is fine, i can't see anything wrong.
I would suggest one thing though, get rid of that singleton session object and use dependency injection, and let the DI container decide what life strategy to use for the Session object at the application composition root.
I hope your case management service is using some kind of ORM . If yes, then it will automatically take care of your Load Case/ Return Case and storing it into the session. And depending on user input when you want to get something from the session and you can use Dependency Injection principle (i would suggest to use Ninject) and achieve it with a singleton pattern .

EF Code First / WPF Application architecture guidance needed

I'm working on a 2-tier WPF/EF Code First application. I did a lot of googling but couldn't find a sample implementation of what I was looking for... was hoping that someone on this forum could help me out. Here are the requirements:
On Application Start up
Open a DBContext
Cache the reference data in various maps/lists when the application starts
Close Context.
When user opens a form
Open a DBContext (I'm using UnitOfWork pattern here)
Fetch a fresh copy of Entity from context for Editing.
Call SaveChanges() when Save button is hit.
Close the Context.
The problem manifests when I use an object from Cache to change a navigation property.
e.g. use a drop down (backed by cache which was created using a different DBContext) to set Department navigation property.
The UnitOfWork either throws an exception saying entity was loaded in another DBContext (When Department is lazy loaded DynamicProxy) or inserts a new row in Department table.
I couldn't find even a single example where reference data was being cached... I can't believe that no one came across this issue. Either I'm not looking in the right place or not using the right keywords.
I hope this is doable using EF. I'd appreciate if you can share your experiences or post some references.
I'm kinda new to this so would like to avoid using too many frameworks and just stick to POCO with WPF/EF stack.
Try to attach your cached item (probably, you'd make a clone before attaching):
var existingUnicorn = GetMyExistingUnicorn();
using (var context = new UnicornsContext())
{
context.Unicorns.Attach(existingUnicorn);
context.SaveChanges();
}
Refer to Using DbContext... article.
You mention you are using WPF for this, in that case you don't necessarily have to open a new DBContext every time you want to interact with the domain layer. (Apologies if this goes against UoW that you are keen on using)
Personally I have been using code-first development for a desktop application, and I have found that pooling the contexts (and therefore the connection) prevents this problem, and hasn't led to any problems thus far.
In principle, as soon as the application is launched, a main Context object is opened for the main UI thread, and stays open throughout the duration of the application lifetime. It is stored statically, and is retrieved by any Repository class when they are used.
For multi-threading scenarios, any background threads are free to open up additional contexts and use them in Repositories to prevent any race conditions.
If you were to adopt this approach, you would find that as all repositories share the same context, there are no issues arising from object context tracking.
I ended up defining int foreign key property in addition to navigation.
In my application I only modify the int property and use the navigation property for displaying the details (read only controls).
While this works it makes the application a little fragile and sometimes inconsistent.
although this blog claims that the FK & Navi properties are synced by EF but I couldn't get it to work.
http://coding.abel.nu/2012/03/ef-code-first-navigation-properties-and-foreign-keys

Where/how should the database code go in a class/application?

So, I don't know if the question is explicit enough, but here's my problem:
I am writing a small application in VB.Net, that retrieves information from a website and present it to the user. Basically, I have written a class, which has a Get(URL) method which retrieves the webpage, reads it and populates the various Properties (Read-only) of the object.
This class works OK.
Now, I would like to store that information in a Database (I'm using Access for now), so that I can read the data from the DB, if the class gets called for a known URL. As I'm fairly new to OOP and completely new to DB usage in desktop applications (no problems in designing the DB though), I am not sure on how to proceed:
Should I put the database code in my existing class?
Should I create an extended class based on the existing one, adding the DB code?
Should I create a completely different class for the DB data and put the switch logic (read from DB or from web) in my application?
...
I realize that my question may sound silly to the most experienced of you, but I'm new to this and I would really like to learn how to do things the right way the first time!!!
Thanks!
This is what I would do:
Create a new class for the database code, and create an
interface for it that it implements.
Then create another class that has the code to fetch the web data. Make it implement the same interface.
Now you can subsitute either class to do your data access from your controller class.
Also, I usually put database and data access in separate projects from my service and ui classes, which are in their own classes, but that might be overkill for your situation.
If you'd like to read more on the subject, look up n-tier application design. The tier you're talking about here is data access.
http://en.wikipedia.org/wiki/Data_access_layer

What is the correct way to solve the ambiguous reference issue in WCF services?

Project Structure
I have a silverlight project SLProj, that references a silverlight class library project called ServiceClients. ServiceClients has two wcf service references, Svc1.svc and Svc2.svc. Both Svc1.svc and Svc2.svc are in two different WCF projects which use the same set of DataContracts which are again in a different class library project called MyDataContracts.dll.
Problem description
Now in my ServiceClients project I get an ambiguous reference issue when I need to use a datacontract class which is present in both the service references. If this were a winforms or webforms project, I could reference the MyDataContracts.dll and reuse the common types. But since, this MyDataContracts.dll was built using a non silverlight class library, it can't be referenced in the silverlight project
Workaround...
I am not sure if this below is the best method to go about taking care of this issue. Can anybody let me know if there is a cleaner way to solve this problem, or is this the best way we have so far?
create a single service reference.
click the 'show all files' button in the solution explorer
drill into the service reference and find Reference.svcmap and open it
find the MetadataSources section
add a second line to include the address to your second service. for example:
MetadataSource Address="http://address1.svc" Protocol="http" SourceId="1"
MetadataSource Address="http://address2.svc" Protocol="http" SourceId="2"
save, close, and update service reference.
Use Automapper
Map the DataContracts with AutoMapper.
You will have to invest some time in understanding AutoMapper and reworking your application. Also AutoMapper adds overhead because all data objects will be mapped. But first you will have a clean solution without hacks and second you gain a decoupled and simple data object layer just for your client. Once done you can forget the mapping but you stay flexible for future changes.
If you never have worked with Automapper it's important to play around with it before starting. Automapper is special and needs some time to familiarise with it.
So there. These are the rough steps:
1. Create a subdirectory and sub-namespace Data and copy the DataContracts. Remove the attributes and properties your client doesn't need because these mapped classes live only in your client. You can also change some types or flatten some complex properties.
2. Create an AutoMapperInit.cs like described at Automapper (read the Getting Started Guide). Use the conflicting references like this:
using ref1 = YourProjectServiceReference1;
using ref2 = YourProjectServiceReference2;
3. Wrap the service client like this:
Example GetExample() {
return AutoMapper.Map<ref1.Example, Example>(ref1.YourService.GetExample());
}
The wrapper also needs the same using directives as in step 2.
4. In this wrapper add a static initializer like this (assuming your wrapper class is called Wrapper):
static Wrapper() {
AutoMapperInit.CreateMaps();
}
5. Omit service references in the client and use using YourClient.Data;, the namespace you created in step 1.
Your client is now decoupled from the service and you don't have conflicts anymore.
Disclaimer: I am not affiliated with AutoMapper. I just used it in a project with a similar problem and am happy with it and wanted to share my experience.
Your workaround is actually quite OK. We've used it in several projects like this with 3 service references. It is actually a workaround for the IDE which for some reason only allows to select one service to create a service reference at a time.
Another thing you could try-out is to multi-target your shared contract to .NET and Silverlight, using the same codebase. Details on how to do such thing is described in http://10rem.net/blog/2009/07/13/sharing-entities-between-wcf-and-silverlight. Might be more work but feel less hacky.

Using a Reference Table Service in a WPF Application

For past projects(the last few have been web using asp.net mvc) we created a service that caches our reference tables(as required) to be used primarily for dropdown lists.
Now I'm working on a desktop application.An upgrade from vb6/sybase to vb.net/sql server
I'm trying out WPF.
I started down the same path building up my DAL. one entity for each reference table.
I'm at the stage now where I want to setup the business layer (some reference tables can be edited)
And I'm not sure if I should follow the same process which is to use ReferenceTableService to "manage" the reference tables.(interacts with the DAL, Controller)
This will be an application that sits on a share that multiple users run.
What's the best way to deal with the reference tables? Caching them doesn't seem to be an option. Should I simply load them as each user opens up a new form in the application? Perhaps using a "ReferenceTableService"?
In this case, the Reference Table Service is thin layer in the application. Not a process running elsewhere.
I haven't done much WPF (be interesting to see what the WPF Gurus think) but I think your existing approach is sound and I don;t see why you should deviate from it.
Loading up on app start sounds reasonable; you just have to think about the expected lifetime of a user session vs the expected frequency of changes to the reference data.
Caching: if the data comes from a central service you could always introduce caching there.

Resources