开发者

Using a WCF service as the model in a WPF application using the MVVM design pattern

When writing a WPF application using MVVM, I want to use a WCF service, with methods on it to provide the relevant data from the applications database.

As an example, if my system has a list of Tasks, they are stored in a SQL database. I can put a method on the Web Service to retrieve all tasks from the database.

I can call this method from a ViewModel and store the results in a

public List<Task> Tasks { get; set; }

Then I would bind a control on my View to this property.

I already have something in place for my View to update, when the Tasks property changed (I didn't put it above to keep t开发者_高级运维he example simple).

My question is, when a new task is added to the database by somebody else, how do I update the Tasks property on the ViewModel?

Do I need to poll the database every x minutes to look for new tasks (Via a method on the WCF service)?

Or can I somehow do something that will update the Tasks property when tasks are added to the database?


You could implement this using the Publish Subscribe Framework for WCF Services. This allows your WPF application to subscribe to updates from the WCF Server. The server would then call WCF Services provided by your WPF application when new data is available. You could then update your view models with the new data. If your WCF Service also controls stores to the database, then you can simply catch the changes as they are made, and send out notifications to your subscribed WPF clients.


You would need to perform some kind of polling to make this work. Changes made to data in your ViewModel are updated directly (via your bindings) because all the changes occur in the WPF app's memory. Changes to the database, though, will only be known to the database.

You might want to add a method to your WCF service that takes a DateTime which will return all tasks added since a given time. Then, call that method from your ViewModel at a frequency that makes sense for your usage scenarios and expected data update rates. At that point, any news tasks added should be reflected in your View.


You could use a CQRS approach depending on the app. If the app is simple CRUD then it's probably not worth it but if you are building a more complex domain model or looking for significant scalability this might be worth investigating. CQRS basically separates your commands from your queries. In your scenario you might have the actual ViewModels stored in the DB with clients getting them directly from there, without needing to go through WCF. You could also have your clients subscribing to domain events to enable them to dynamically refresh as required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜