C# : Dependency Injection in C# using Autofac

  • Autofac: Dependency Injection framework for C# :

Other DI frameworks for dot net platform (Alternatives of AutoFac ):




Below are some features of Autofac:


Definition: 




Application Refactoring:  


Installation :






AUTOFAC MODULARITY FEATURE:



Examples :
  • InstancePerDependency()
Configure the component so that every dependent component or call to Resolve()
gets a new, unique instance (default).

builder.RegisterType<BlogSearcher>().As<IBlogSearcher>().InstancePerDependency();

  • SingleInstance()
Configure the component so that every dependent component or call to Resolve()
gets the same, shared instance.

builder.RegisterType<BlogSearcher>().As<IBlogSearcher>().SingleInstance();

  • InstancePerLifetimeScope()
Configure the component so that every dependent component or call to Resolve()
within a single ILifetimeScope gets the same, shared instance. 

Dependent components in different lifetime scopes will get different instances.

builder.RegisterType<MvcContext>().As<IMvcContext>().AsSelf().InstancePerLifetimeScope();

  • InstancePerRequest()
Share one instance of the component within the context of a single web/HTTP/API
request. 

Only available for integration that supports per-request dependencies
(e.g., MVC, Web API, web forms, etc.).

builder.RegisterType<Glass.Mapper.Sc.Web.RequestContext>().As<Glass.Mapper.Sc.Web.IRequestContext>().AsSelf().InstancePerRequest();


That's all folks :)

Comments