1
請參閱下面的代碼:實例化類型使用AutoMapper與DI容器
public class Test : ITest
{
public ITest2 _iTest2;
public int _id;
public string _name;
public Test(ITest2 test2)
{
_iTest2 = test2;
}
}
public interface ITest
{
}
public class Test2 : ITest2
{
}
public interface ITest2
{
}
public class Test3 : ITest3
{
public int _id;
public string _name;
}
public interface ITest3
{
}
我已經在我的Global.asax如下:
Mapper.Initialize(m =>
{
m.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));
});
我可以在我的客戶端應用程序映射類型這樣做:
cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));
如何映射使用Castle Windsor的類型而不必使用新的關鍵字Test和Test2?
我讀到另一個答案,有人建議這樣做:
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn(typeof(IValueResolver<,,>)));
// container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn<IValueResolver>());
container.Register(Types.FromThisAssembly().BasedOn<Profile>().WithServiceBase());
var profiles = container.ResolveAll<Profile>();
// Add your list of profiles to the mapper configuration here
Mapper.Initialize(m => {
m.ConstructServicesUsing(container.Resolve);
profiles.ToList().ForEach(p => m.AddProfile(p));
});
// I'm not sure about this as I haven't used AutoMapper for a while,
// but I assume you want to resolve the static mapper instance
container.Register(Component.For<IMapper>().Instance(Mapper.Instance));
}
我必須這樣做:
cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>().ConstructUsing(opt => new BusinessLayer.Test(new BusinessLayer.Test2()));
還是應該AutoMapper能夠使用這種映射類型:
cfg.CreateMap<DataLayer.Test3, BusinessLayer.Test>()
什麼代碼要說的是:「當你想創建一個新的服務,從Windsor容器中獲取「。使用[服務定位器反模式](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/)這樣的事情可能是要走的路。 – stuartd
@stuartd,需要什麼AutoMapper配置才能使代碼在上面工作,即Castle Windsor和AutMapper? – w0051977
對不起,自從我上次使用Castle之後,我已經記得太久以至於無法記住我的頭頂。 – stuartd