c# - MVVM - How to use a given REST-API dll -
i'm starting learn mvvm in c# mvvmlight. other project, have given (but self-made) rest-api dll. dll i'm trying use in new project. completly based on api. i'm unsure "model"-part , don't want repeat myself while coding.
problem this: application has several "plugins/sections". let's @ sample "groups" section. api defines groups-entity-class properties "groupname, permissions, members". then, application must have groups model , groupsviewmodel , groupsview ui. there, must list/show "groupname, permissions, members".
question is: have redeclare properties dll-entity-class in mvvm-model-class? or best way use rest api? there pattern. read extension object pattern. have no clue.
hint: since api written myself (only classes, no mvvm or other frameworks), modify needed.
thanks in advance!
take @ repository pattern: https://msdn.microsoft.com/en-us/library/ff649690.aspx. basically create repository api calls, , transforms entities format can use in view.
if the objects api sufficient can return them, otherwise convert them in repository more useful.
in viewmodel ask repository return the model, , need not care how and in format got them.
small example:
interface iapirepository { task<observablecollection<apimodel>> getapimodelsasync(); } class apirepository : iapirepository { private async task<observablecollection> getapimodelsasync() { var mycollection = new observablecollection<apimodel>(); var result = await domyapicall(); foreach (result item) { var newmodel = new apimodel(); newmodel.fillfromapi(item); mycollection.add(newmodel); } return mycollection; } } class myviewmodel : viewmodelbase { private readonly iapirepository _apirepository; public myviewmodel(iapirepository apirepository) { _apirepository = apirepository; initializeviewmodel(); } private observablecollection<apimodel> _apimodels; public observablecollection<apimodel> apimodels { { return _apimodels; } set { set(ref _apimodels, value); } } private async void initializeviewmodel() { //as repo finished apimodels raise raisepropertychanged event apimodels = await _apirepository.getapimodelsasync(); } } //in viewmodellocator simpleioc.default.register<iapirepository, apirepository>(); simpleioc.default.register<myviewmodel>(); //construct viewmodel (with injected repository) var vm = simpleioc.default.getinstance<myviewmodel>();
with of pattern can do other awesome things:
- if add new data source need change repository , not viewmodel.
- if want test view (for example in design mode) can inject a
mockapirepository
which returns sample data instead of doing api call
Comments
Post a Comment