Skip to main content

13 posts tagged with "C#"

View All Tags

Dynamically create generic C# object using reflection | 动态创建C#泛型实例

· One min read

Classes referenced by generic type:

public class Cat
{
...
}
public class Dog
{
...
}

Generic class:

public class Animals<T>
{
public Animals(int id, T body)
{
Id = id;
Body = body;
}

public int Id { get; set; }

public T Body { get; set; }
}

Create instance for generic class dynamically:

using System;
using Newtonsoft.Json;

namespace RtxService.Api
{
public class Program
{
public static void Main(string[] args)
{
var cat = new Cat()
{
...
};

var type = typeof(Cat);
var genericType = typeof(Animals<>).MakeGenericType(type);
var animal = Activator.CreateInstance(
genericType,
1,
JsonConvert.DeserializeObject(cat, type));
}
}
}

refs: https://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection

Consume AutoMapper in a Singleton instance during impliment an IHostedService

· One min read

AutoMapper 中的 AddAutoMapper 默认使用 AddScoped 方式把 AutoMapper 实例注册到.NET Core DI 中的:

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

如果你在一个 IHostedService 注册了一个 Singleton 实例, 该 Singleton 实例的构造函数中通过 DI 注入的方式引用了 IMapper, 将会发生如下错误:

'Cannot consume scoped service 'AutoMapper.IMapper' from singleton 'XXX'.'

解决方法是把 IMapper 也以 Singleton 模式注册:

public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<SourceClass, DestinationClass>();
}
}
public void ConfigureServices(IServiceCollection services)
{
...
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new AutoMapperProfile());
});

IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
...
}

Refs:

https://stackoverflow.com/questions/40275195/how-to-setup-automapper-in-asp-net-core

ClustrMaps