c# - MVVM - injecting model into viewmodels vs. getting model via singleton -
in application model dataset representing database , @ point in execution of application there should 1 model object. created when application starts , stored property in application class. viewmodels receive reference dataset/model via constructors.
seeing there can 1 dataset, better implement singleton class create/return dataset , have viewmodels reference (are there problems approach)?
thanks, james
from personal experience, rocksolid approach:
- you prevent instantiation of more 1 instance of dataset
- you have globally available, want , makes life easy
however, oop-zealots argue should not use classical gang of 4 singleton (with static instance property), di singleton, object created di container once , passed everywhere.
personally, think tradeoff: gof singleton easy use , simple. i've never had case had replace or database-access in general. have interface database access , if in need change implementation within singleton (and enhance it, possible during runtime). can save lot of boilerplate code, keep in mind model tightly coupled database , can't exist without it.
the sole advantage of di stuff can see can configure external config doubt lifecycle management of database access ever change, other advantage of di. , objectmodel might kept cleaner in long run (plus big projects).
i use generic singleton implementation. object fetishists argue again it's more wrapper singleton, it's job , allows keep objectmodels ("as opposed viewmodels", don't wrong) pure don't need implement them singletons static members:
public class singleton<t> t : class { static object syncroot = new object( ); static t instance; public static t instance { { if ( instance == null ) { lock ( syncroot ) { if ( instance == null ) { constructorinfo ci = typeof( t ).getconstructor( bindingflags.nonpublic | bindingflags.instance, null, type.emptytypes, null ); if ( ci == null ) { throw new invalidoperationexception( "class must contain private constructor" ); } instance = (t)ci.invoke( null ); } } } return instance; } } }
http://www.sanity-free.com/132/generic_singleton_pattern_in_csharp.html
Comments
Post a Comment