Autofac with WebApi & Business Layer

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 11:43:05

If you use constructor injection (and it`s really a good idea). First you need is add to add reference to Autofac.WebApi2 assembly via Nuget. Lets think that your controllers are in the different Assembly that the host (Service.dll or somethink like this) then you

Services Project with all our controllers:

public class DependenyInitializer
{

   public static readonly DependenyInitializer Instance = new DependenyInitializer();

      private DependenyInitializer()
        {
          var builder = new ContainerBuilder();
          builder.RegisterModule<BusinessLayerModule>(); // register all dependencies that has been set up in that module
          builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
          this.Container = builder.Build();
        }

public IContainer Container { get; }

}

Buisness Layer

you`ll have to create a module

  using System.Reflection;
  using Autofac;
  using DataAccessLayer;
  using Module = Autofac.Module;

 public class BusinessLayerModule : Module
  {
     protected override void Load(ContainerBuilder builder)
      {
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces(); // that links all clases with the implemented interfaces (it they mapped 1:1 to each other)
      }

Hosting (WebApiConfig.cs in Register(HttpConfiguration config))

  var container = DependenyInitializer.Instance.Container;
  config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

Main compexity here is knowing that you need Autofac.WebApi2 and it`s RegisterApiControllers. Try that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!