3

I am very new to AutoFac and am trying to use it for my new project with WebApi and Business Layer with contracts and their respective implementations.

I have written the IocConfiguration for webapi and invoke from global.asax.

However, for my Business Logic how do I setup all my contracts and implementations with autofac?

I did go through some tutorials online but however I could not find anything helpful, If someone has a sample app, links that really helps.

Edit:

AutoMapper profile.

public class CustomProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<MyViewModel, MyModel>()
            .ForMember(d => d.Id, s => s.MapFrom(src => src.Id));
    }
}

Edit:

After few long hours spent on this I figured out how to setup AutoMapper 4.2.1 with AutoFac. Apparently I was using ConfigurationStore in AutoMapper 3.3.0 but I upgraded to 4.2.1 the profile registration changed a little bit. Below is what worked for me.

public class AutoMapperModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<MyProfile1>();
            cfg.AddProfile<MyProfile2>();
        });

        base.Load(builder);
    }
}
Immortal
  • 1,233
  • 4
  • 20
  • 47

1 Answers1

4

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.

Vladimir
  • 1,380
  • 2
  • 19
  • 23
  • Thank you very much for the response. I have my webapi and business in different projects, i have my business manager contracts in a different project. so i inject the interface of the business manager in the web api controller constructor. As suggested i have written a BusinessLayerModule, however they do not get invoked on bootstrap. However the businesslayermodule does not bootstrap. Obviously I have not registered the module, builder.RegisterModule() Is my approach correct? – Immortal Apr 09 '16 at 08:15
  • Your approach looks correct. You use a DependencyInitializer in your project ? All dependencies actually registered there in builder.Build() only after that you can use them – Vladimir Apr 09 '16 at 08:25
  • Write a comment if you still have issues, I`ll try to help then – Vladimir Apr 09 '16 at 10:40
  • Thank you very much, apart from AutoFac I am also using AutoMapper for mapping viewmodels to my db models, I am using IMappingEngine and MappingEngine as registertype, it does not seem to work. I have my Mapper setup between my viewmodel and domain models. Also I have a problem with managing EF Context instance through Autofac, as the bootstrap is on WebApi layer and i have a repository layer and beyond my business layer does not really know about db and its context, how do I manage my context instances using autofac in my scenario. I update the question. – Immortal Apr 09 '16 at 15:05
  • 1
    About automapper and autofac http://stackoverflow.com/questions/33980760/how-to-inject-automapper-with-autofac would be usefull. About Entity framework contexts - if you have dll (Data Access Layer) then should also have there a module with the register of corresponding types and interfaces. And it`s a good idea to made context eater SingleInstance() - or singleton or have usual binding like I`ve shown in BusinessLayerModule . Singleton might be usefull if you updating a data – Vladimir Apr 11 '16 at 07:46
  • 1
    Thank you very much for your inputs. I found and fixed the issue from the AutoMapper documentation and their source code. I am using 4.2.1 and not previous versions, hence the way we setup has changed a little bit. – Immortal Apr 11 '16 at 23:24