我正在使用 DryIoc 和 ExpressMapper。
我将 ExpressMapper 包装在另一个类中,并且在某些时候它应该用于映射到具有参数化构造函数的类型。实际上是当我将视图模型映射到业务模型时。该参数是存储库类的实例。
使用 TDD,我的 Mapper 类以这样的方式结束(注意接受 Func 的构造函数)。
public class Mapper<T1, T2> : IMapper<T1, T2>
{
private readonly MappingServiceProvider _mapper;
public Mapper()
{
_mapper = new MappingServiceProvider();
_mapper.Register<T1, T2>();
}
public Mapper(Func<T2> func)
{
_mapper = new MappingServiceProvider();
_mapper.Register<T1, T2>().Instantiate((t1) => func());
}
public T2 Map(T1 t)
{
return _mapper.Map<T1, T2>(t);
}
}
因此,我尝试像这样使用 Ioc:
Func<IActivitiesModel>factoryActivitiesModel = () => container.Resolve<IActivitiesModel>();
container.Register(Made.Of(() => factoryActivitiesModel));
// () => new ActivitiesModel(container.Resolve<IActivityRepository>(IfUnresolved.Throw)
container.Register<IMapper<ActivitiesViewModel, IActivitiesModel>, Mapper<ActivitiesViewModel, IActivitiesModel>>(Reuse.Singleton, Made.Of(
() => new Mapper<ActivitiesViewModel, IActivitiesModel>(Arg.Of<Func<IActivitiesModel>>())
));
但它没有。
Unable to use null factory object with factory method ActivitiesMVC.Ioc.<>c__DisplayClass4_0::System.Func`1[ActivitiesLogic.Models.IActivitiesModel] factoryActivitiesModel when resolving: Func<ActivitiesLogic.Models.IActivitiesModel>.
无论如何,我后来尝试了不同的方法,但似乎都没有奏效。
我想避免将容器存储为静态单例并让映射器依赖它(我希望映射器保持 Ioc 不可知)。
如何实现?
编辑:当前解决方案(静态单例错误)
public class Ioc
{
public class Factory<T> : IFactory<T>
{
public T Create()
{
return Container.Resolve<T>();
}
}
private static Lazy<Container> _container;
public static Container Container => _container.Value;
static Ioc()
{
_container = new Lazy<Container>(GetContainer);
}
static private Container GetContainer()
{
var container = new Container(rules => rules
//.WithoutThrowOnRegisteringDisposableTransient()
.WithTrackingDisposableTransients());
container.Register(Made.Of(() => new ActivityController(Arg.Of<IMapper<ActivitiesViewModel, IActivitiesModel>>())));
container.Register<ILabContext, LabContext>(new SingletonReuse());
container.Register<IActivityRepository, ActivityRepository>(new SingletonReuse());
container.Register<IActivitiesModel>(made: Made.Of(() => new ActivitiesModel(Arg.Of<IActivityRepository>())));
container.Register(typeof(IFactory<>), typeof(Factory<>), new SingletonReuse());
container.Register<IMapper<ActivitiesViewModel, IActivitiesModel>, Mapper<ActivitiesViewModel, IActivitiesModel>>(Reuse.Singleton, Made.Of(
() => new Mapper<ActivitiesViewModel, IActivitiesModel>(Arg.Of<IFactory<IActivitiesModel>>())
));
container.Register<IMapper<ActivitiesModel, ActivitiesEntity>, Mapper<ActivitiesModel, ActivitiesEntity>>(new SingletonReuse(), Made.Of(
() => new Mapper<ActivitiesModel, ActivitiesEntity>()
));
return container;
;
}
}