c# - Cannot use Unity dependency in constructor -


i'm running issue can't seem find solution to, because don't understand how fix nullreferenceexception.

i have constructor;

public mainviewmodel() {     this.refresh = new delegatecommand(this.dorefresh);     //...more this...     //...and finally...     this.initializeobjects(); } 

then somewhere between properties there dependency

[dependency] public iunitycontainer container { get; set; } 

and initializeobjects-method generating nullreferenceexception on 'container'

private void initializeobjects() { using (var context = this.container.resolve<idbcontextscope>()) {     //...remainder of method... } } 

the exception thrown @ 3rd row of block of code, row starting 'using (var ...'

the exception argumentnullexception;

message "value cannot nul.parameter name: container" source = microsoft.practices.unity stacktrace = @ microsoft.practices.unity.unitycontainerextensions.resolve....etc.. 

so concrete questions are; indeed iunitycontainer container throwing exception? why throw exception? how work around this?

edit:

as found in first 2/3 comments under post, cause of nullreferenceexception asserted. however, i still don't know how work around it, don't experience every-day nre. function needing container there initialize values program needs function, , therefore needs called inside constructor. afaik can't declare dependency, how work around this..?

the problem dependency properties this

[dependency] public iunitycontainer container { get; set; } 

is aren't available within constructor. if must use value within constructor, use constructor dependency

public mainviewmodel(iunitycontainer muhcontainer, someotherdependency derp) {     // use muhcontainer , derp here } 

in general if object must have dependency, should supplied via constructor injection. if have dependency has acceptable default, might want change @ runtime via configuration, property injection fine.

[dependency] public herp whocares  {     { return _herp ?? _defaultherpdoesntmatterlol; }     set { _herp = value; } } 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -