GithubHelp home page GithubHelp logo

automapper.extensions.microsoft.dependencyinjection's Introduction

This package and repository have been deprecated and archived. Its code is folded in to the main AutoMapper repository.

automapper.extensions.microsoft.dependencyinjection's People

Contributors

alsami avatar benmccallum avatar braincrumbz avatar bruno-garcia avatar grishat avatar jbogard avatar jholovacs avatar lbargaoanu avatar say25 avatar sliekens avatar stefh avatar sungam3r avatar talagozis avatar tasteful avatar wdspider avatar

Stargazers

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

Watchers

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

automapper.extensions.microsoft.dependencyinjection's Issues

Extension Doesn't Work with AutoMapper 6.2.0 In Integration Tests

When integration testing with ASP.Net Core, it is very common to use TestServer to start your service as an in-memory host so that you can perform service-level integration tests via a real HttpClient.

However, since AutoMapper 6.2.0 was released this no longer works. Your Startup class is effectively called multiple times within the same process, so the AddAutoMapper() call happens multiple times, so the Mapper.Initialize() call also happens multiple times. This results in an exception in the second test:

System.InvalidOperationException : Mapper already initialized. You must call Initialize once per application domain/process.
   at AutoMapper.Mapper.set_Configuration(IConfigurationProvider value)
   at AutoMapper.Mapper.Initialize(Action`1 config)
   at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`1 additionalInitAction, IEnumerable`1 assemblies)
   at MyService.Startup.ConfigureServices(IServiceCollection services)

How can we 'clear out' the AutoMapper statics so that integration testing can be supported in a single process?

Is there a way I could pass the injected IMapper to an extension method?

I am not sure if I am asking the right question but here is what I wanted to do. Is there a better way to do this?

    public static class CustomerExtensions
    {
        public static CustomerViewModel ToViewModel(this Customer customer, IMapper mapper)
        {
            return mapper.Map<Customer, CustomerViewModel>(customer);
        }
    }

Profiles with dependencies

If I have a profile with a dependency, is there any way of it being automatically picked up by AddAutomapper? I'm currently getting an error about parameterless constructors.

I've tried manually adding it using the cfg => overload of AddAutomapper, but it appears to still try and auto-register the profiles.

Do I have to revert to my own custom setup?

Suggestion: IMapper<T>

We have somewhat special requirements in our application:

  1. We need to map the same src/dst type pairs differently in different parts of our project
  2. We need access to a scoped IServiceProvider in our mappings

The proposed solution to those problems is having a default IMapper<T> where T : IConfigurationProvider or something similar.

We evaluated the following implementations:

  • IMapper<T> where T : IConfigurationProvider

    This seems to be the most flexible solution.

  • IMapper<T> where T : Profile

    There doesn't seem to be a way to merge profiles by using AddProfile from within a profile which makes this solution unusable.

  • IMapper<T1> where T : Profile and overloads with IMapper<T1, T2>, etc...

    Too much boilerplate for us.

The implementation with T : IConfigurationProvider was the most flexible for us even though we need (in the worst case) both a IConfigurationProvider implementation and a Profile derived class for a single mapping, like e.g.:

public class MyProfile1 : Profile
{
    public MyProfile1()
    {
        // Mapping configuration
    }
}

Someone would be able to create its own class derived from MapperConfiguration:

public class MyConfiguration : MapperConfiguration
{
    public MyConfiguration(MyProfile profile)
        : base(cfg => cfg.AddProfile(profile))
    {
    }
}

A generic implementation of a profile configuration could look like this (even though I don't really like this solution):

public class ProfileConfiguration<T> : MapperConfiguration where T : Profile
{
    public ProfileConfiguration(T profile)
        : base(cfg => cfg.AddProfile(profile))
    {
    }
}

public class ProfileConfiguration<T1, T2> : MapperConfiguration where T1 : Profile, T2 : Profile
{
    public ProfileConfiguration(T1 profile1, T2 profile2)
        : base(cfg => { cfg.AddProfile(profile1); cfg.AddProfile(profile2); })
    {
    }
}

We add all classes derived from MapperConfiguration and Profile to our service collection which allows us to use IMapper<MyConfiguration> (or IMapper<ProfileConfiguration<MyProfile>>) in a constructor which gets resolved to Mapper<MyConfiguration> (or Mapper<ProfileConfiguration<MyProfile>>) which looks like this:

public class Mapper<T> : IMapper<T>
    where T : IConfigurationProvider
{
    private readonly IMapper _mapper;

    public Mapper(IServiceProvider serviceProvider, T t)
    {
        _mapper = new Mapper(t, serviceProvider.GetService);
    }

    public IConfigurationProvider ConfigurationProvider => _mapper.ConfigurationProvider;

    // ... remaining implementation

All those types are registered with:

serviceCollection
    .Scan(scan => scan.FromAssemblyOf<Startup>().AddClasses(c => c.AssignableTo<Profile>()).AsSelf().WithSingletonLifetime())
    .Scan(scan => scan.FromAssemblyOf<Startup>().AddClasses(c => c.AssignableTo<IConfigurationProvider>()).AsSelf().WithSingletonLifetime())
    .AddScoped(typeof(IMapper<>), typeof(Mapper<>))

The Scan function is from the Scrutor package. This project would/should probably avoid using Scrutor and use its own implementation instead (as it already does).

The usage would look like this:

public class MyController
{
    public MyController(IMapper<MyConfiguration> mapper)
    {
    }
}

Object instances created with default values when combining AddAutoMapper, AddDataReaderMapping, and Profiles

When combining AddAutoMapper(), AddDataReaderMapping(), and Profile classes, a destination object instance's properties are populated with type default values and not with source object values.

(Hopefully this is the right repo for this issue. I wasn't sure if this one or AutoMapper.Data was appropriate.)

Types

Source

IDataRecord shape is similar to

@FirstName NVARCHAR(50),
@LastName NVARCHAR(50),
@UserId INT

Destination

User.cs

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int UserId { get; set; }
}

Behavior

Expected

Object instance looks like

{
    FirstName: "TestFirstName",
    LastName: "TestLastName",
    UserId: 123
}

Actual

Object instance looks like

{
    FirstName: null,
    LastName: null,
    UserId: 0
}

Steps to reproduce

Versions

AutoMapper.Data 1.0.1
AutoMapper.Extensions.Microsoft.DependencyInjection 3.2.0
Microsoft.AspNetCore.All 2.0.6
Microsoft.EntityFrameworkCore.SqlServer 2.0.2

Startup.cs

services.AddAutoMapper(config => config.AddDataReaderMapping());

UserProfile.cs

public class UserProfile : Profile
{
    public UserProfile()
    {
        this.CreateMap<IDataRecord, User>();
    }
}

UserController.cs

public class UserController : Controller
{
    private DbContext dbContext;
    private IMapper mapper;

    public UserController(DbContext dbContext, IMapper mapper)
    {
        this.dbContext = dbContext;
        this.mapper = mapper;
    }

    public async Task<IActionResult> GetAsync()
    {
        ...
        var dataReader = await command.ExecuteReaderAsync();

        await dataReader.ReadAsync();

        var user = this.mapper.Map<IDataRecord, User>((IDataRecord)dataReader);
        ...
    }
}

Workarounds

Either delete UserProfile.cs and modify Startup.cs:

services.AddAutoMapper(config => {
    config.AddDataReaderMapping();
    config.CreateMap<IDataRecord, User>();
});

Or be more explicit in UserProfile.cs:

public class UserProfile : Profile
{
    public UserProfile()
    {
        this.CreateMap<IDataRecord, User>()
            .ForMember(destination => destination.FirstName, options => options.MapFrom(source => source.GetString(source.GetOrdinal("FirstName"))))
            ... etc;
    }
}

"Mapper not initialized" error after Upgrading to 5.0.1 from 4.0.1

After I upgraded to 5.0.1 from 4.0.1 I get the following error:

Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance

I have the following line in startup.cs ConfigureServices:
services.AddAutoMapper(typeof(Startup));

I also have a MappingProfile.cs with the following structure:

public class MappingProfile : Profile {
  public MappingProfile() {
    CreateMap<....
  }
}

This was sufficient in 4.0.1 but apparently not in 5.0.1

AddAutoMapper to return IServiceCollection: allow chaining

Consider returning IServiceCollection from all overloads of AddAutoMapper.
That would allow chaining all calls to the multiple 'AddSomething'.

Same approach is taken by AddSwaggerGen from Swashbuckle.SwaggerGen and AddHangfire from Hangfire.AspNetCore. As well as the packages built by Microsoft.

DI within the profiles?

For one of my mappings, I need access to some configuration element, so ideally I'd love to be able to do this:

public class MappingProfile : Profile 
{
    public MappingProfile(IOptions<Settings> options) {

        CreateMap<User, EditUserModel>(MemberList.Source)
            .ForMember(m => m.Something,
                o => o.MapFrom(a => a.GenerateThing(options.SomeConfigItem)));

But that's not supported - can you advise how I might achieve this?

Thanks

Initialization doesn't work

When automapper-calling code like ProjectTo<>() is called I receive:

An unhandled exception occurred while processing the request.
InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

This code used to work before updating a bunch of nugets to the latest versions.

In startup I'm using
services.AddAutoMapper(typeof(Startup));

.Net core DI and the static mapper

Just coming from AutoMapper/AutoMapper#2140 I actually got my setup to work as initially expected.

Although, when using static mapping after having done:

services.AddAutoMapper() .AddTransient<CustomResolver, DefaultCustomResolver>();

The mapping configuration looks like:

...
.ForMember(dest => dest.SomeDate, opt => opt.ResolveUsing<CustomResolver>())

Ends up with the following stacktrace when mapping with Mapper.Map :

at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Activator.CreateInstance(Type type) at AutoMapper.MappingOperationOptions2.CreateInstance[T]() at lambda_method...

It seems that the static mapper does not get/uses the IServiceProvider.GetService method supplied when setting up the IMapper instance in .AddAutoMapper()?

Injecting and using the IMapper instance and doing the same mapping works as expected with the injected Resolver.

Problems targeting to net461

Targeting console application to net461 throws Could not load file or assembly error.
I have tried to install following NuGet packages:

AutoMapper.Extensions.Microsoft.DependencyInjection
AutoMapper
Microsoft.Extensions.DependencyInjection

`
// Set DI
var serviceCollection = new ServiceCollection();
ConfigureService(serviceCollection);
var serviceProvider = serviceCollection.BuildServiceProvider();

private static void ConfigureService(IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<IApplicationBusiness, ApplicationBusiness>();
`

Signed Assembly

Is there a signed version of this assembly? If not, would you be willing to produce one?

Thank you for your trouble.

[Feature Request] Add IApplicationBuilder Extension Method For Mapper.AssertConfigurationIsValid() Functionality

Would it be possible to add an IApplicationBuilder extension method that adds the functionality that Mapper.AssertConfigurationIsValid() provided to non .NET Core based projects?

I'm envisioning my Startup class to look something like this:

public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		services.AddAutoMapper(typeof(MyMappingProfile));
	}
	
	public void Configure(IApplicationBuilder app, IHostingEnvironment env)
	{
		if (env.IsDevelopment())
		{
			app.UseDeveloperExceptionPage();
			app.AssertAutoMapperConfigurationIsValid();
		}
	}
}

Ideally, this would make the assert exceptions to be thrown when a request is made to the server in much the same way that adding Mapper.AssertConfigurationIsValid() to Global.asax - Application_Start() in .NET based projects did.

NOTE: I did attempt to simply use Mapper.AssertConfigurationIsValid(); however, it did not assert properly. I assume this is due to needing to use the non-static IMapper which does not currently have the AssertConfigurationIsValid() method.

IValueResolver DI issues

Hello,

I'm having issues injecting IHttpContextAccessor into my custom value resolver. When I try to inject the service using the default dotnet core DI, AutoMapper seems to expect that my resolver uses a default constructor and I get the error message: Property: Url ---> System.MissingMethodException: No parameterless constructor defined for this object.

This is the call in my profile that is throwing the exception:

      CreateMap<AppointmentType, AppointmentTypeViewModel>()
      .ForMember(model => model.Url,
      opt => opt.ResolveUsing<SolutionUrlResolver>())
      .ReverseMap();

Here's my Resolver:

namespace View
{
  public class SolutionUrlResolver : IValueResolver<SolutionEntity, SolutionViewModel, string>
  {
    public const string URLNAME = "GetAppointmentTypes";
    private IHttpContextAccessor _httpContextAccessor;

    public SolutionUrlResolver(IHttpContextAccessor httpContextAccessor) {
      _httpContextAccessor = httpContextAccessor;
    }

    public string Resolve(SolutionEntity source, SolutionViewModel destination, string destMember, ResolutionContext context)
    {
      var url = (IUrlHelper)_httpContextAccessor.HttpContext.Items[BaseController.URLHELPER];
      return url.Link(URLNAME, new { id = source.Id});
    }
  }
}

In Startup.cs I have this:

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
      services.AddAutoMapper();
      services.AddMvc(); ...

When I replace the SolutionUrlResolver with a class that uses a default constructor (and does not reference IHttpContextAccessor) then the exception goes away.

I tried mimicking the way DependencyResolver is written in the test app. I must be missing something simple here but I just don't know what it is.

.net core 2.0 xunit integration test

Hi, i have an error after upgrade to .net core 2.0 from 1.1 when try run integration test with xunit framework, but when i comment services.AddAutoMapper(); in the ConfigureServices(IServiceCollection services) from Startup class it works fine

 public class ThingsController_Tests
    {
        private readonly HttpClient _client;
        public ThingsController_Tests()
        {
            var hostBuilder = new WebHostBuilder();

            
            var server = new TestServer(hostBuilder.UseStartup<Startup>());
            this._client = server.CreateClient();
        }
...

packages from my test project, it has link to main project

<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.0.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
    <PackageReference Include="xunit.runner.console" Version="2.2.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
    <PackageReference Include="xunit" Version="2.2.0" />
    <PackageReference Include="xunit.runners" Version="2.0.0" />

automapper packages in main project

<PackageReference Include="automapper" Version="6.1.1" />
   <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="3.0.1" />

help pls :)

at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeAssembly.get_DefinedTypes()
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`1 additionalInitAction, IEnumerable`1 assembliesToScan)
   at myProjectName.Startup.ConfigureServices(IServiceCollection services) in myProjectPath
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
   at Tests_myprojectName.ThingsController_Tests..ctor() in myProjectPath
Result Message:	System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.

Adding AutoMapper Breaks Scaffolding

When I add AutoMapper and the AutoMapper DI for ASP.NET Core. It breaks the MVC scaffolding.
This is a newly created project so no major customizations...

Finding the generator 'controller'...
Running the generator 'controller'...
Attempting to compile the application in memory with the modified DbContext
Attempting to figure out the EntityFramework metadata for the model and DbContext: Donor
Exception has been thrown by the target of an invocation. StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection exportServices)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EntityFrameworkServices.TryCreateContextUsingAppCode(Type dbContextType, ModelType startupType)
Object reference not set to an instance of an object. StackTrace:
There was an error creating the DbContext instance to get the model. No parameterless constructor defined for this object. at AutoMapper.ServiceCollectionExtensions.AddAutoMapper(IServiceCollection services, Action`1 additionalInitAction, DependencyContext dependencyContext)

No parameterless constructor defined for this object. at Tikanagan.Web.Startup.ConfigureServices(IServiceCollection services)

at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
RunTime 00:00:09.88

Support IMappingAction.

While scanning an assembly for IValueResolver, IMemberValueResolver, ITypeConverter in AddAutoMapper overloads it would be handy if Automapper could also recognize IMappingAction

What's the point of using the package?

I don't want to sound rough, but I would like to know a sample usage to understand why anyone would use this.

What are the benefits of injecting AutoMapper into the DI mechanism of ASP.NET Core? Does it make AutoMapper able to construct object with dependencies using the integrated ASP.NET's DI container?

For now, the only think I have seen is that I can inject an instance of the mapper using a IMapper mapper in the constructor of my controller, but that doesn't offer much advantages. Previously, I used the state Mapper façade.

DI into ITypeConverter

Hi,
I'm trying to inject a service into a ITypeConverter but it doesn't work.
To be more specific I'm getting this message:

Mapping types:
Source2 -> Dest2
TestApp.Source2 -> TestApp.Dest2

Type Map configuration:
Source2 -> Dest2
TestApp.Source2 -> TestApp.Dest2

Property:
ResolvedValue ---> System.MissingMethodException: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at AutoMapper.MappingOperationOptions`2.CreateInstance[T]()
   at lambda_method(Closure , Object , Object , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , Object , Object , ResolutionContext )
   at AutoMapper.Mapper.AutoMapper.IMapper.Map[TDestination](Object source)
   at TestApp.Program.Main(String[] args) in C:\Projects\OpenSource\AutoMapper.Extensions.Microsoft.DependencyInjection\src\TestApp\Program.cs:line 24}	AutoMapper.AutoMapperMappingException

What I did to replicate this problem is to extend the test class included into the repo with this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TestApp
{
	using System.Reflection;
	using AutoMapper;
	using Microsoft.Extensions.DependencyInjection;
	using System.Threading;
	using System.Threading.Tasks;

	public class Program
	{
		public static void Main(string[] args)
		{
			IServiceCollection services = new ServiceCollection();
			services.AddTransient<ISomeService>(sp => new FooService(5));
			services.AddAutoMapper(typeof(Source));
			var provider = services.BuildServiceProvider();
			var mapper = provider.GetService<IMapper>();

			var result = Mapper.Map<Dest2>(new Source2()
			{
				Text = new MyComplexType()
				{
					Text = "Ciao",
				}
			});

			foreach (var service in services)
			{
				Console.WriteLine(service.ServiceType + " - " + service.ImplementationType);
			}
			Console.ReadKey();
		}
	}

	public class Source
	{
	}

	public class Dest
	{
	}

	public class Source2
	{
		public MyComplexType Text { get; set; }
	}

	public class Dest2
	{
		public int ResolvedValue { get; set; }
		public string LocalizedValue { get; set; }
	}

	public class Profile1 : Profile
	{
		public Profile1()
		{
			CreateMap<Source, Dest>();
		}
	}

	public class Profile2 : Profile
	{
		public Profile2()
		{
			CreateMap<Source2, Dest2>()
				.ForMember(d => d.ResolvedValue, opt => opt.ResolveUsing<DependencyResolver>());
		}
	}

	public class DependencyResolver : IValueResolver<object, object, int>
	{
		private readonly ISomeService _service;

		public DependencyResolver(ISomeService service)
		{
			_service = service;
		}

		public int Resolve(object source, object destination, int destMember, ResolutionContext context)
		{
			return _service.Modify(destMember);
		}
	}

	public interface ISomeService
	{
		int Modify(int value);
	}

	public class FooService : ISomeService
	{
		private readonly int _value;

		public FooService(int value)
		{
			_value = value;
		}

		public int Modify(int value) => value + _value;
	}

	public class MyComplexTypeStringConverter : ITypeConverter<MyComplexType, string>
	{
		private readonly ISomeService service;

		public MyComplexTypeStringConverter(ISomeService service)
		{
			this.service = service;
		}

		public string Convert(MyComplexType source, string destination, ResolutionContext context)
		{
			return source.Text;
		}
	}

	public class MyComplexType
	{
		public string Text { get; set; }
	}
}

I'm pretty sure I did something wrong, but what?
Thanks

AssertConfigurationIsValid not working into extension method AddAutoMapper

I'm trying configure Automapper at Startup.cs, but AssertConfigurationIsValid not actually do at application start.

            services.AddAutoMapper(cfgExpression => 
            { 
                cfgExpression.AddProfile<MappingProfile>(); 
                cfgExpression.Advanced.BeforeSeal(cfgProvider => cfgProvider.AssertConfigurationIsValid<MappingProfile>());
            });

If add Mapper.Configuration.AssertConfigurationIsValid(); after call extension AddAutoMapper AssertConfiguration works as expected.

Is this the correct behavior?

ProjectTo exposes a previously fixed EF Core bug where incorrect data returned for queries projecting a single constant from a subquery.

dotnet/efcore#10946

Error:

Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at Microsoft.EntityFrameworkCore.Query.Expressions.SelectExpression.BindSubqueryProjectionIndex(Int32 projectionIndex, IQuerySource querySource)
at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)

Working code example with sqlite

  1. clone
  2. dotnet restore
  3. dotnet run

The issue is caused by two thing that I can see:

  • OrderBy + ThenBy using the same column.
  • ProjectTo using a class that creates a join. IE including a nav property.

Im pretty perplexed by this, the EF core issue above was supposed to have been fixed. I think the projection is somehow bringing it back to life.

DebugView

.Call System.Linq.Queryable.Select(
    .Call System.Linq.Queryable.ThenBy(
        .Call System.Linq.Queryable.OrderBy(
            .Constant<Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[EFCore.Models.Cat]>(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[EFCore.Models.Cat]),
            '(.Lambda #Lambda1<System.Func`2[EFCore.Models.Cat,System.Int32]>)),
        '(.Lambda #Lambda2<System.Func`2[EFCore.Models.Cat,System.Int32]>)),
    '(.Lambda #Lambda3<System.Func`2[EFCore.Models.Cat,EFCore.Models.CatViewModel]>))

.Lambda #Lambda1<System.Func`2[EFCore.Models.Cat,System.Int32]>(EFCore.Models.Cat $x) {
    $x.MeowLoudness
}

.Lambda #Lambda2<System.Func`2[EFCore.Models.Cat,System.Int32]>(EFCore.Models.Cat $x) {
    $x.MeowLoudness
}

.Lambda #Lambda3<System.Func`2[EFCore.Models.Cat,EFCore.Models.CatViewModel]>(EFCore.Models.Cat $dtoCat) {
    .New EFCore.Models.CatViewModel(){
        Breed = .If ($dtoCat.Breed == null) {
            null
        } .Else {
            .New EFCore.Models.CatBreedViewModel(){
                BreedName = ($dtoCat.Breed).BreedName,
                Cats = .Call System.Linq.Enumerable.ToList(.Call System.Linq.Enumerable.Select(
                        ($dtoCat.Breed).Cats,
                        .Lambda #Lambda4<System.Func`2[EFCore.Models.Cat,EFCore.Models.CatViewModel]>)),
                Id = ($dtoCat.Breed).Id
            }
        },
        Id = $dtoCat.Id,
        MeowLoudness = $dtoCat.MeowLoudness,
        Name = $dtoCat.Name,
        TailLength = $dtoCat.TailLength
    }
}

.Lambda #Lambda4<System.Func`2[EFCore.Models.Cat,EFCore.Models.CatViewModel]>(EFCore.Models.Cat $dtoCat) {
    .New EFCore.Models.CatViewModel(){
        Id = $dtoCat.Id,
        MeowLoudness = $dtoCat.MeowLoudness,
        Name = $dtoCat.Name,
        TailLength = $dtoCat.TailLength
    }
}

Ignoring unmapped members after ConvertUsing

From @paradisehuman on December 19, 2016 22:44

this is my code :

public class UserProfile:Profile
{
    public UserProfile()
    {
        CreateMap<UserViewModel, ApplicationUsers>().ConvertUsing<UserEncryptor>();
    }

}
public class UserEncryptor : ITypeConverter<UserViewModel, ApplicationUsers>
{
    private readonly IConfigurationRoot _configuration;
    public UserEncryptor(IConfigurationRoot configuration)
    {
        _configuration = configuration;
    }

    public ApplicationUsers Convert(UserViewModel source, ApplicationUsers destination, ResolutionContext context)
    {
        if (context==null||source == null) return null;
        var aes = new Common.EncryptionAes(_configuration[key: "Keys:AesKey"]);
        return new ApplicationUsers
        {
            UserName = aes.EncryptAes(source.Username),
            Email = aes.EncryptAes(source.Email),
            PhoneNumber = aes.EncryptAes(source.MobileNumber),
            User = new User
            {
                FirstName = aes.EncryptAes(source.FirstName),
                LastName = aes.EncryptAes(source.LastName),
                Gender = aes.EncryptAes(source.Gender.ToString()),
                ProfileImage = aes.EncryptAes(source.ProfileImage.FileName)
            }
        };
    }
}

Note that ApplicationUsers is inherited from IdentityUser Class.
When I tested this mapping,I got this error :

System.NullReferenceException: Object reference not set to an instance of an object.

I know this error is for that some members are not ignored. Something like this

CreateMap<UserViewModel ,ApplicationUsers >()
.ConvertUsing(converter=> new ApplicationUsers(){
Email = converter.Email,
....
});

will help me because by default ignore rest of the members but the problem is that if I want to use this kind of code, I cant encrypt my members because I don't access to DI configuration for profile.Because profile is parameter less.

I need something similar to upper code that can implement in ITypeConverter functions.

Anyone has any solution ?

Copied from original issue: AutoMapper/AutoMapper#1859

udpate nuget package with automapper 6.0.0

Great jbogard, please be kind to update the nuget package that work with automapper 6.0.0

Build started, please wait... C:\Program Files\dotnet\sdk\1.0.1\Microsoft.Common.CurrentVersion.targets(1964,5): warning MSB3277: Found conflicts between different versions of the same dependent assembly that could not be resolved. These reference conflicts are listed in the build log when log verbosity is set to detailed. [F:\S2\xxx.cms\src\xxx.cms\xxx.cms.csproj] Startup.cs(30,13): error CS1705: Assembly 'AutoMapper.Extensions.Microsoft.DependencyInjection' with identity 'AutoMapper.Extensions.Microsoft.DependencyInjection, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null' uses 'AutoMapper, Version=5.0.2.0, Culture=neutral, PublicKeyT oken=be96cd2c38ef1005' which has a higher version than referenced assembly 'AutoMapper' with identity 'AutoMapper, Version=0.0.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005' [F:\S2\xxx.cms\src\xxx.cms\xxx.cms.csproj] C:\Program Files\dotnet\sdk\1.0.1\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.targets(92,5): error : Cannot find project info for 'F:\S2\xxx.cms\src\xxx.cms\xxx.cms.csproj'. This can indicate a missing project reference. [F:\S2\xxx.cms\test\xxx.Cms.IntgratedTests\xxx.Cms. IntgratedTests.csproj]

Prevent consumers from not adding marker types or assemblies for profile discovery

I feel like it's quite easy to call services.AddAutoMapper() with no parameters and expect for things to Just Work™. Unfortunately, without adding at least a marker type or an assembly to drive the profile discovery, consumers will get a mapping exception later at runtime because no profiles were added to the configuration.

I guess people expect it to work since many of the default, Microsoft-provided extension methods do something when called with no parameters. On the other hand, I totally understand AutoMapper needs information to do its thing properly.

What do you think of adding a check in this overload for marker types and this one for assemblies to verify the array contains at least one element?

Or delegate it to AddAutoMapperClasses to check whether the initialisation action is not null or we have at least one assembly? But then we can't know which extension method the consumer used, hence difficult to give them a specific error message.

Just opening a discussion here, will be happy to provide a PR when/if we agree on something. As an FYI, this comes from that SO question.

Edit:

I just realised that if in an ASP.NET Core app targeting netcoreapp1.0, then the nestandard1.6 flavour is used, so calling services.AddAutoMapper() would call the parameter-less overload that uses the DependencyContext. Same thing happens if the app targets the full .NET framework. I guess we should know more about the setup, then.

Unrelated question, what's the need for a netstandard1.1 build of that library? Can the application use a Startup from another project which would be a class library?

Question: ambigous call AddAutoMapper.

I just upgraded to AutoMapper 6.0.0 and this assembly (2.0.0) and now receive the error:

The call is ambiguous between the following methods or properties: 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, Action, params Assembly[])' and 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, Action, params Type[])' Jbssa.FreightRates.Web d:\jbs\FreightRates\src\Jbssa.FreightRates.Web\Startup.cs

The specific line of code is:

services.AddAutoMapper(cfg =>
{
     cfg.CreateMap<DateTimeOffset, DateTime>().ConvertUsing<DateTimeOffsetConverter>();
     cfg.CreateMap<DateTime, DateTimeOffset>().ConvertUsing<DateTimeConverter>();
     cfg.CreateMap<DateTimeOffset?, DateTime?>().ConvertUsing<NullableDateTimeOffsetConverter>();
     cfg.CreateMap<DateTime?, DateTimeOffset?>().ConvertUsing<NullableDateTimeConverter>();
});

This hasn't changed for a while and is being used in many projects. What solution would you recommend?

I also tried the follwoing with the same issue:

private class DateProfile : Profile
{
    public DateProfile()
    {
        CreateMap<DateTimeOffset, DateTime>().ConvertUsing<DateTimeOffsetConverter>();
        CreateMap<DateTime, DateTimeOffset>().ConvertUsing<DateTimeConverter>();
        CreateMap<DateTimeOffset?, DateTime?>().ConvertUsing<NullableDateTimeOffsetConverter>();
        CreateMap<DateTime?, DateTimeOffset?>().ConvertUsing<NullableDateTimeConverter>();
     }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(cfg => cfg.AddProfile(new DateProfile()));
}

AddAutoMapper and WebApplicationFactory do not play nice.

Sample app.

I tried to use the absolute bare minimum code from basically dotnet new mvc && dotnet new xunit where I AddAutoMapper and I also have two tests class using a pretty much empty WebApplicationFactory. I also tossed a single profile in the mvc app. This was incredibly easy to reproduce.

Mapper.Reset(); in my startup did not help, as well as disabling UseStaticRegistration.

If I just use a single WebApplicationFactory then my tests do not fail so is this some weird thread issue with IClassFixture? From my research there should not be two separate instances of a fixture created in xunit but this could be wrong. Somehow, my startup is being initialized multiple times.

Any help is appreciated. I feel like this is an important issue because the official Microsoft tutorial and example shows how to write tests using the new WebApplicationFactory as shown here and anyone with two XUnit test classes inheriting from their implementation of the factory will run into this very error and their tests will fail. For what its worth, I am not running my tests in parallel.

ref #26 (comment)

[5.0.1] Doesn't register user-defined profiles

As of 5.0.1 services.AddAutoMapper(); doesn't register user-defined mapping Profiles from the executing assembly. Immediate subsequent call of Mapper.AssertConfigurationIsValid(); throws an InvalidOperationException:

image

But 4.0.1 works just fine.

Env: ASP.NET Core 2.1.

Where condition in scanning of dependency context breaks compatibility with msbuildproject types

Background
We have a Visual Studio solution with multiple projects. The main project is an ASP.NET Core Web Application, which currently solely targets .NET Framework. The other projects are partly .NET Core Class Libraries (also only targeting .NET Framework) and normal Class Libraries (especially for COM interop services).
So far we used to have AutoMapper automatically scan the assemblies of the default DependencyContext for any contained profiles etc.

Problem
With the latest changes for version 1.1.0, in particular this commit, the compatibility with normal Class Libraries has been broken. These are not contained any more in the list of assemblies to scan, even if they reference the AutoMapper library and contain profiles etc.

Cause
The problem comes from the fact that the RuntimeLibrary.Dependencies for these libraries does only contain other normal Class Libraries, not the AutoMapper assembly. The Where condition thus excludes these.

Suggestion
You could handle the normal Class Libraries differently (i.e. always include them), notable from the different Type they have, being "msbuildproject". The .NET Core ones have "project".

services.AddAutoMapper() breaks EF Core CLI

When I run the dotnet ef database drop command, it throws exception:

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Mapper already initialized. You must call Initialize once per application domain/process.
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

It seems to caused by services.AddAutoMapper() in ASP.NET Core ConfigureServices method. When I comment this line, command works fine. I tried other commends like database update or migrations, this problem won't happen.

Solution from #36 works. But I think the default extension method shouldn't break EF Core CLI.

I'm using AutoMapper 6.2.2 and AutoMapper.Extensions.Microsoft.DependencyInjection 3.2.0, with Entity Framework Core 2.1.0-preview1-final.

Required explicit dependency on Automapper

Probably an odd one that no-one else will run into...

If I have only "AutoMapper.Extensions.Microsoft.DependencyInjection" defined in the dependencies section of a project.json the project will compile and run but not pick up any assemblies to load configuration from.

Adding an explicit reference to "AutoMapper" to the project.json fixes this.

This is due to https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/src/AutoMapper.Extensions.Microsoft.DependencyInjection/ServiceCollectionExtensions.cs#L31

I don't think a change to code is required, though it might be worth adding something to the Readme / any tutorials to explicitly reference AutoMapper.

Move initial configuration to `Configure` in .NET Core

I don't believe it is currently possible to correctly register dependency injection with AutoMapper in .NET Core. Consider the following code inside ConfigureServices:

services.AddAutoMapper(cfg =>
{
     cfg.ConstructServicesUsing(services.BuildServiceProvider().GetService);
});

I have a value resolver that depends on Entity Framework's database context. The call to services.BuildServiceProvider() returns a new instance of service provider that has its own collection of services. Here is the relevant code from ServiceCollectionContainerBuilderExtensions:

return new ServiceProvider((IEnumerable<ServiceDescriptor>) services, options);

I don't think there is any other way to get a service provider inside Configure. This means that AutoMapper will inject a different instance of database context than the one used by my domain services. This causes issues when both contexts use the same entity. I can probably hack my way around this somehow, but the same issue applies to all injected services. If you set up a service as a singleton, then you end up with two "singletons" (I have verified this using a static field incremented in the constructor).

I think this can be resolved by adding AutoMapper middleware in ConfigureServices and configuring it in Configure. Configure has access to the default, and already instantiated, service provider. That way you could pass this provider to ConstructServicesUsing.

To sum it up, the code could look something like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAutoMapper(cfg =>
    {
        cfg.ConstructServicesUsing(app.ApplicationServices.GetService);
    });
}

exception resolving IMapper in tests

In integration tests (with MSTest & TestServer), all tests throw InvalidOperationException "Cannot resolve scoped service 'AutoMapper.IMapper' from root provider". Changing the IMapper registration from Scoped to Transient allows the tests to pass.

Running AutoMapper 6.2.1 because of AutoMapper/AutoMapper.Data#30

Test results including error message...

Test Name: OnGet_NoFound
Test FullName: MyCompany.MyApp.Test.RazorPages.EmployeeInfoPageTest.OnGet_NoFound
Test Source: C:\src\MyApp\MyCompany.MyApp.Test\RazorPages\EmployeeInfoPageTest.cs : line 70
Test Outcome: Failed
Test Duration: 0:00:00.1919067

Result StackTrace:
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at MyCompany.MyApp.Test.RazorPages.EmployeeInfoPageTest.TestInit() in C:\src\MyApp\MyCompany.MyApp.Test\RazorPages\EmployeeInfoPageTest.cs:line 35
Result Message: Initialization method MyCompany.MyApp.Test.Unit.RazorPages.EmployeeInfoPageTest.TestInit threw exception. System.InvalidOperationException: Cannot resolve scoped service 'AutoMapper.IMapper' from root provider..
Result StandardOutput:
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\jmeyer\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.

Test startup class is as follows...

namespace MyCompany.MyApp.Test
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.TestHost;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using MyCompany.MyApp.Core.Repositories;
    using MyCompany.MyApp.Test.RepositoryMocks;

    [type: TestClass]
    public class TestsStartup
    {
        public static TestServer TestServer { get; private set; }

        public static IConfiguration Configuration { get; private set; }

        public static IServiceProvider ServiceProvider => TestServer.Host.Services;

        [method: AssemblyInitialize]
        public static void InitializeContext(TestContext testContext)
        {
            if (testContext.Properties.TryGetValue("ASPNETCORE_ENVIRONMENT", out var environment))
            {
                Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", (string)environment, EnvironmentVariableTarget.Process);
            }

            string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", EnvironmentVariableTarget.Process) ?? EnvironmentName.Production;

            Configuration = new ConfigurationBuilder()
                .SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
                .AddJsonFile("appsettings.json", optional: true)
                .AddJsonFile($"appsettings.{environmentName}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

            TestServer = new TestServer(WebHost.CreateDefaultBuilder<Web.Startup>(Array.Empty<string>())
                .UseEnvironment(environmentName)
                .UseConfiguration(Configuration)
                .ConfigureTestServices(ConfigureTestServices));
        }

        public static void ConfigureTestServices(IServiceCollection serviceCollection)
        {
            serviceCollection.Remove(serviceCollection.First(sd => sd.ServiceType == typeof(IEmployeeRepository) && sd.Lifetime == ServiceLifetime.Transient));
            serviceCollection.AddTransient<IEmployeeRepository, EmployeeRepositoryMock>();
        }
    }
}

Remove option to register statically and do instance-only

Big problems with registering statically:

services.AddAutoMapper is called on an instance of a IServiceCollection, but Mapper.Initialize is static. I can't know if AddAutoMapper has already been called with against the same IServiceCollection instance. Even if I track if I've already initialized AutoMapper statically, I can't know if it's against the same set of services.

Just far more trouble than it's worth, I think.

Please add support for calling AddAutoMapper() multiple times

Please consider adding support for calling AddAutoMapper() multiple times.

Reason:
We have very modular application design, each module is responsible of registering own mapper profiles.
Currently services.AddAutoMapper(i => i.AddProfile(...)); cannot be called multiple times because of Mapper.Initialize being overwriting previous setup. Additionally services are not added with TryAdd...

AutoMapper.Extensions.Microsoft.DependencyInjection Dependency on custom Resolver not working in ASP.NET Core 2.0 project

In my ASPNET Core 2.0 project, when adding a Cache Dependency to my CustomResolver, such dependency is not resolved. I have a complex dependency structure and many mapping profiles which I register as below:

`
services.AddSingleton<ICacheService, CacheService>();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new CreateProductProfile());
cfg.AddProfile(new ChangeProductProfile());
cfg.AddProfile(new SharedProfile());
cfg.AddProfile(new RetrieveProductProfile());
});

        var mapper = config.CreateMapper();
        services.AddSingleton(mapper);

`
My resolver CustomResolver has below code:

`
public class ProductIdResolver : IValueResolver<Request.Product, Entities.Product, int>
{
private readonly ICacheService cacheService;

    public ProductIdResolver(ICacheService cacheService)
    {
        this.cacheService = cacheService;
    }

    public Entities.Product Resolve(Request.Product source, Entities.Product destination, int destMember, ResolutionContext context)
    {
        if (source == null)
            return null;

        var product = Mapper.Map<Entities.Product>(source);

        product.Id = TranformProductId(source);

        return product;
    }

    private int TranformProductId(Request.PBI source)
    {
        var frombase = cacheService.GetProducts().FirstOrDefault(p => p.Sku == source.Sku);

        if (frombase == null)
            throw new NullReferenceException("Invalid Product");

        return frombase.Id;
    }
}

`

The resolver reference is inside my SharedProfile, which is called by both Create and Change profile (I broke those profile classes into a third one for code re-using).
The problem is that my CacheService is not being resolved by DI and I always get an "Error mapping types" exception.
For reference, my code works if I remove the CacheService object.

How can I successfully inject that dependency into my custom resolver?

how to config IMapper inject Singleton

I see the source code below:
return services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
but i want to use singleton ?

Resolving of Profiles using DI

Hello, gentlemen.
Thank you for a Great Tool.
Is it possible to add a resolving of profiles with DI? When I am trying to use .AddAutoMapper(expression => expression.AddProfile<AutoMapperProfile>) extension method, it requires an parameterless constructor because of where TProfile : Profile, new() restriction in the IMapperConfigurationExpression interface. Also I can't add an instance of my AutoMapperProfile class with .AddProfile(autoMapperProfile), because of resolving of a profiles by their types anyway ( https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/src/AutoMapper.Extensions.Microsoft.DependencyInjection/ServiceCollectionExtensions.cs#L206). As workaround I am using this approach:

.AddTransient<IMapper>(provider => new Mapper(new MapperConfiguration(expression => expression.AddProfile(provider.GetService<AutoMapperProfile>()))))
.AddTransient<AutoMapperProfile>()

but it would be nice to use out of the box .AddAutoMapper method from ServiceCollectionExtensions.
Thanks a lot

AspNetCore Dependency

Hi Jimmy,

It looks like in v5 of this library you have taken on an AspNetCore dependency, but we use this in an MVC5 apps, console apps, as well as AspNetCore apps. It looks like the reason for the dependency is the ConfigurationAssertMiddleware. Do you think it makes sense for this to be in a separate package? It seems weird to me to have AutoMapper.Extensions.Microsoft.DependencyInjection depend on an AspNetCore package.

Thanks! :)

Referencing an assembly

Hello,

I'm using this package in my dotnet core application and I don't understand how to reference an assembly this way: services.AddAutoMapper(<my_assembly>)

The only way I know how to reference an assembly is with the using keyword. I realize this is probably a C# question and not a question about this package, but google keeps pointing me to the using keyword.

I'm looking for the magic words to search for in google or a concrete example I can study that uses services.AddAutoMapper(<some_assembly_in_a_solution>)?

Thanks.

Issue With Microsoft.Extensions.DependencyModel, Version=1.1.1

Updated to the latest AspNetCore.Mvc versions 1.1.2 with using the framework net452 I get the error at the bottom.

The setup in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
   services.AddCors(options =>
   {
      options.AddPolicy("AllowSpecificOrigin",
         builder => builder.WithOrigins("http://localhost:16964"));
   });

   services.AddMvc();
   services.Configure<MvcOptions>(options =>
         {
            options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
         });
   services.AddAutoMapper();

... other services
}

The error

System.IO.FileLoadException was unhandled
  FileName=Microsoft.Extensions.DependencyModel, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
  FusionLog=""
  HResult=-2146234304
  Message=Could not load file or assembly 'Microsoft.Extensions.DependencyModel, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  Source=AutoMapper.Extensions.Microsoft.DependencyInjection
  StackTrace:
       at AutoMapper.ServiceCollectionExtensions.AddAutoMapper(IServiceCollection services)
       at Api.Enterprise.Startup.ConfigureServices(IServiceCollection services) in "Project Path Removed Main project folder"\Startup.cs:line 99
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
       at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
       at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
       at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
       at Api.Enterprise.Program.Main(String[] args) in "Project Path Removed Main project folder"\Program.cs:line 18
  InnerException: 
       FileName=Microsoft.Extensions.DependencyModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
       FusionLog==== Pre-bind state information ===
LOG: DisplayName = Microsoft.Extensions.DependencyModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
 (Fully-specified)
LOG: Appbase = file:///"Project Path Removed Main project folder"/bin/Debug/net452/win7-x64/
LOG: Initial PrivatePath = NULL
Calling assembly : AutoMapper.Extensions.Microsoft.DependencyInjection, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: "Project Path Removed Main project folder"\bin\Debug\net452\win7-x64\Enterprise.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 1.0.0.0 redirected to 1.1.0.0.
LOG: Post-policy reference: Microsoft.Extensions.DependencyModel, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
LOG: Attempting download of new URL file:///"Project Path Removed Main project folder"/bin/Debug/net452/win7-x64/Microsoft.Extensions.DependencyModel.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Build Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

       HResult=-2146234304
       Message=Could not load file or assembly 'Microsoft.Extensions.DependencyModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
       InnerException: 

The references are happy
image

The new version 3.x.x doesn't find Profile classes.

@jbogard

I upgraded my project to V3.x.x and it crashes in the mapping like:
Mapper.Map<model1>(model2);

I have the services.AddAutoMapper(); at Startup.cs and my profile classes with Profile class inheritance.

I did the downgrade to 2.0.1 and it started to work fine again.

What changed? It's a bug or have new way to configure?

I'm unable to add DependancyInjection, incompatible with 'all' frameworks

Hi, I'm using npm to install this after adding AutoMapper successfully. but I'm getting this error:

error: Package 'AutoMapper.Extensions.Microsoft.DependancyInjection' is incompatible with 'all' frameworks in project 'D:\angular\vega\Vega.csproj'.

I tried with different versions of both AutoMapper and AutoMapper.Extensions.Microsoft.DependancyInjection but no luck. what should I do?

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.