-
Notifications
You must be signed in to change notification settings - Fork 331
Dependency Injection
chaowlert edited this page Jun 5, 2020
·
5 revisions
PM> Install-Package Mapster.DependencyInjection
This plugin allows you to inject service into mapping configuration.
On startup, register TypeAdapterConfig
, and ServiceMapper
.
public void ConfigureServices(IServiceCollection services)
{
...
var config = new TypeAdapterConfig();
// Or
// var config = TypeAdapterConfig.GlobalSettings;
services.AddSingleton(config);
services.AddScoped<IMapper, ServiceMapper>();
...
}
NOTE: lifetime of ServiceMapper
is up to services you would like to inject. It can be singleton, if you inject only singleton services. Or it can be transient, if any injected services is transient.
You can get service by MapContext.Current.GetService<>()
, for example
config.NewConfig<Poco, Dto>()
.Map(dest => dest.Name, src => MapContext.Current.GetService<INameFormatter>().Format(src.Name));
If you setup service injection, you need to use mapper instance to map object.
public class FooService {
private readonly IMapper _mapper;
public FooService(IMapper mapper) {
_mapper = mapper;
}
public void DoSomething(Poco poco) {
var dto = _mapper.Map<Dto>(poco);
...
}
}
- Configuration
- Config inheritance
- Config instance
- Config location
- Config validation & compilation
- Config for nested mapping
- Custom member matching logic
- Constructor mapping
- Before & after mapping
- Setting values
- Shallow & merge mapping
- Recursive & object references
- Custom conversion logic
- Inheritance