Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Registering Autofac & AutoMapper Circularly
public static void Main(string[] args)
{
var components = RegisterComponents();
Run(components);
}
private static IContainer RegisterComponents()
{
var builder = new ContainerBuilder();
builder.RegisterType<PreMapperComponent>().As<IPreMapperComponent>();
builder.Register(ConfigureMapper).SingleInstance();
builder.RegisterType<PostMapperComponent>().As<IPostMapperComponent>();
return builder.Build();
}
private static void Run(IContainer container)
{
var mapper = container.Resolve<IMapper>();
var source = new EntityType(123, "Test-text", "Test-description");
var dto = mapper.Map<DtoType>(source);
dto.RunComponents();
}
private static IMapper ConfigureMapper(IComponentContext context)
{
var configuration = new MapperConfiguration(config =>
{
var ctx = context.Resolve<IComponentContext>();
config.CreateMap<EntityType, DtoType>()
.ConstructUsing(_ =>
new DtoType(ctx.Resolve<IPreMapperComponent>(), ctx.Resolve<IPostMapperComponent>()));
});
return configuration.CreateMapper();
}
public interface IPreMapperComponent
{
void Run();
}
public class PreMapperComponent : IPreMapperComponent
{
public void Run()
{
Console.WriteLine("PreMapperComponent.Run executed.");
}
}
public interface IPostMapperComponent
{
void Run();
}
public class PostMapperComponent : IPostMapperComponent
{
public void Run()
{
Console.WriteLine("PostMapperComponent.Run executed.");
}
}
public class DtoType
{
private readonly IPostMapperComponent _postComponent;
private readonly IPreMapperComponent _preComponent;
public DtoType(IPreMapperComponent preComponent, IPostMapperComponent postComponent)
{
_preComponent = preComponent;
_postComponent = postComponent;
}
public int Id { get; set; }
public string Text { get; set; }
public void RunComponents()
{
_preComponent.Run();
_postComponent.Run();
}
}
public class EntityType
{
public EntityType(int id, string text, string description)
{
Id = id;
Text = text;
Description = description;
}
public int Id { get; set; }
public string Description { get; set; }
public string Text { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment