Reputation: 1262
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);
}
}
Upvotes: 3
Views: 1196
Reputation: 1390
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.
Upvotes: 4