Coder Social home page Coder Social logo

automapper.contrib.autofac.dependencyinjection's Introduction

AutoMapper.Contrib.Autofac.DependencyInjection

Build Application codecov

NuGet NuGet

This is a cross platform library, written in .netstandard 2.0, that serves as an extension for autofac's containerbuilder. It will register all necessary classes and interfaces of Jimmy Bogard's AutoMapper implementation to the autofac-container so you can use AutoMapper and object-mapping right ahead without worrying about setting up required infrastructure code.

Installation

This package is available via nuget. You can install it using Visual-Studio-Nuget-Browser or by using the dotnet-cli

dotnet add package AutoMapper.Contrib.Autofac.DependencyInjection

If you want to add a specific version of this package

dotnet add package AutoMapper.Contrib.Autofac.DependencyInjection --version 1.0.0

For more information please visit the official dotnet-cli documentation.

Usage sample

After installing the package you define your entities and dtos and create profiles for them.

public class Customer
{
	public Guid Id { get; }
	public string Name { get; }
	
	public Customer(Guid id, string name)
	{
		Id = id;
		Name = name;
	}
}

public class CustomerDto
{
	public Guid Id { get; }
	public string Name { get; }

	public CustomerDto(Guid id, string name)
	{
		Id = id;
		Name = name;
	}
}

public class CustomerProfile : Profile 
{
	public CustomerProfile()
	{
		CreateMap<Customer, CustomerDto>()
			.ConstructUsing(user => new UserDto(user.Id, user.Name))
			.ReverseMap()
			.ConstructUsing(userDto => new User(userDto.Id, userDto.Name));
	}
}

public static class Program
{
	public static void Main(string args[])
	{
		var containerBuilder = new ContainerBuilder();
		// here you have to pass in the assembly (or assemblies) containing AutoMapper types
		// stuff like profiles, resolvers and type-converters will be added by this function
		containerBuilder.RegisterAutoMapper(typeof(Program).Assembly);
		
		var container = containerBuilder.Build();

		var mapper = container.Resolve<IMapper>();

		var customer = new Customer(Guid.NewGuid(), "Google");

		var customerDto = mapper.Map<CustomerDto>(customer);
	}
}

Support for Property Injection

You can set propertiesAutowired to true to enable property based injection, just modify the prior example like so:

public static class Program
{
	public static void Main(string args[])
	{
		var containerBuilder = new ContainerBuilder();
		
		// Update this line with the setting:
		containerBuilder.RegisterAutoMapper(typeof(Program).Assembly, propertiesAutowired: true);
		
		var container = containerBuilder.Build();

		var mapper = container.Resolve<IMapper>();

		var customer = new Customer(Guid.NewGuid(), "Google");

		var customerDto = mapper.Map<CustomerDto>(customer);
	}
}

Validating your configuration

AutoMapper allows the user to validate their mappings. This should only be done within a test project, since it's time-consuming

var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterAutoMapper(typeof(Program).Assembly);

var container = containerBuilder.Build();
var mapperConfiguration = container.Resolve<MapperConfiguration>();

// this line will throw when mappings are not working as expected
// it's wise to write a test for that, which is always executed within a CI pipeline for your project.
mapperConfiguration.AssertConfigurationIsValid();

automapper.contrib.autofac.dependencyinjection's People

Contributors

alsami avatar benmccallum avatar lbargaoanu avatar mattrhoden avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

automapper.contrib.autofac.dependencyinjection's Issues

How to use

Once this is installed, how do I configure and use it? Where should I put my maps?

IValueConverter registering is not supported

Hello,

It seems that IValueConverter implementations are not supported in the AutoMapperModule.
I tried to use an implementation of IValueConverter in my code, thinking that the registration would be done automatically with this great package but I got an error indicating that my implementation was not registered.
Therefore, I used an IValueResolver as a workaround.

Thanks for the great work done.

AutoMapper V13 support

Upgrade

<PackageReference Include="AutoMapper" Version="12.0.1" />

to

<PackageReference Include="AutoMapper" Version="13.0.1" />

Different constructor for adding the profiles?

Salutations.

I was trying to implement a profile that took constructors:

public class CustomProfiler : Profiler
{
    public CustomProfiler(ISomething something) {}
}

However, it didn't work since it required an empty constructor. Looking at the code, it appears that the culprit is this line.

            foreach (var profile in profiles.Select(profile => profile.GetType())) 
                cfg.AddProfile(profile);

However, when I looked at the interface above, I saw this overload on the class:

        /// <summary>
        /// Add an existing profile
        /// </summary>
        /// <param name="profile">Profile to add</param>
        void AddProfile(Profile profile);

With that, it looks like the above loop could just be changed to:

            foreach (var profile in profiles) 
                cfg.AddProfile(profile);

That method was added in 2016, so I'm curious of the reasoning for using the type version instead of the instance. I hacked a local copy and it seems to work, but you may have additional insight I'm missing.

Thank you.

Calling multiple times for different assemblies

I need the ability to invoke RegisterAutoMapper() multiple times, each time with a different assembly. The expectation is that this should register the core AutoMapper types only once, but allow different mapping profiles to be registered based on the assembly provided.

Stack overflow has a question similar to this, but only contains a solution for the MS IoC container. Is there a similar solution for Autofac?

The automatic mapping is faulty

I use autofac to replace the container,This is the injection method
builder.RegisterAutoMapper((config) => { config.ReplaceMemberName("_", ""); }, ThisAssembly, true);

Entity class

public string? UNIT_STATUS_REMARKS { get; set; }
public string? REMARKS { get; set; }

Dto
public string? UnitStatusRemarks { get; set; }

public string? Remarks { get; set; }

mapping

CreateMap<SamplePosInfoCreateDto, TB_SAMPLE_POS_INFO>();

When I only assign values to the dto's Remark, UNIT_STATUS_REMARKS mapped entities also have values, and hopefully someone will be able to answer them and give a solution

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.