c# - Autofac in console applications (convention) -


i use autofac in console application. first usage. before using in asp.net mvc only. in mvc project can setup autofac in global.asax, inject iservice controller , can more , less works. in console application below:

internal class program {     private static icontainer container { get; set;}      private static void main(string[] args)     {          container = container.configure(); // here have necessary objects set          // can use in main method as:          using (var scope = container.beginlifetimescope())          {              scope.resolve<isomething>();          }     } } 

as can see usage of simple in main method. how using in external class? let create class cat, , inside use autofac. should pass contructor object container class program? e.g.:

cat cat = new cat(program.container, "molly"); 

or maybe should create icontainer inside cat class?

what best solution?

only console application needs know autofac, otherwise you're falling onto service locator pattern, considered anti-pattern. instead, application should follow pattern:

//in console application using (var scope = container.beginlifetimescope()) {     iserviceservice = scope.resolve<iservice>();     service.execute(); }  class someservice : iservice {     readonly isomedependency _dependency;      public someservice(isomedependency dependency)     {         _dependency = dependency;     }      public void execute()     {         _dependency.dosomething();     } }  interface iservice {     void execute(); } 

notice never call constructor. make habit never "new up" object unless object poco (contains data, no logic).

note isomedependency can depends on 0 or more other classes, takes via constructor injection. since autofac created iservice, , of dependencies, including isomedependency, of isomedependency's dependencies initialized, , forth way down. video demonstrating concept miguel castro's deep dive dependency injection , writing decoupled quality code , testable software.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -