根据配置,有条件地 return 对象 Locator.CurrentMutable.Register?
Conditionally return object with Locator.CurrentMutable.Register, based on configuration?
我有一个应用程序,我想从文件系统或 Amazon S3 load/save 附件 - 取决于它是 运行 在云中还是在本地桌面 PC 上。
以下是我到目前为止所写的内容:
public class AppBootstrapper
{
public bool Cloud { get; set; }
public AppBootstrapper()
{
Cloud = false;
RegisterDependencies();
}
public void RegisterDependencies()
{
Locator.CurrentMutable.Register( () => {
if ( Cloud ) return new AmazonS3Repo();
return new FileRepo() as IAttachmentRepo;
}, typeof(IAttachmentRepo) );
}
}
当然,这意味着您必须使 AppBootstrapper
成为单例(以便设置 Cloud
属性)并且失去了依赖倒置的好处.如果我能做到这一点就好了:
Locator.CurrentMutable.Register<bool>( cloud => {
if ( cloud ) return new AmazonS3Repo();
return new FileRepo() as IAttachmentRepo;
})
但是,我想我说的是依赖注入(这不是 Splat
设计的目的)。有没有其他方法可以使用 Splat
?
是的,你只需要使用 Register 和 GetService 的 contract 参数。
Locator.CurrentMutable.Register(() => new AmazonS3Repo(), “AmazonS3”, typeof(IAttachmentRepo));
Locator.CurrentMutable.Register(() => new FileRepo(), “FileRepo”, typeof(IAttachmentRepo));
然后
var service = Locator.Current.GetService(typeof(IAttachmentRepo), cloud ? "AmazonS3" : "FileSystem");
希望这对你有用!
我有一个应用程序,我想从文件系统或 Amazon S3 load/save 附件 - 取决于它是 运行 在云中还是在本地桌面 PC 上。
以下是我到目前为止所写的内容:
public class AppBootstrapper
{
public bool Cloud { get; set; }
public AppBootstrapper()
{
Cloud = false;
RegisterDependencies();
}
public void RegisterDependencies()
{
Locator.CurrentMutable.Register( () => {
if ( Cloud ) return new AmazonS3Repo();
return new FileRepo() as IAttachmentRepo;
}, typeof(IAttachmentRepo) );
}
}
当然,这意味着您必须使 AppBootstrapper
成为单例(以便设置 Cloud
属性)并且失去了依赖倒置的好处.如果我能做到这一点就好了:
Locator.CurrentMutable.Register<bool>( cloud => {
if ( cloud ) return new AmazonS3Repo();
return new FileRepo() as IAttachmentRepo;
})
但是,我想我说的是依赖注入(这不是 Splat
设计的目的)。有没有其他方法可以使用 Splat
?
是的,你只需要使用 Register 和 GetService 的 contract 参数。
Locator.CurrentMutable.Register(() => new AmazonS3Repo(), “AmazonS3”, typeof(IAttachmentRepo));
Locator.CurrentMutable.Register(() => new FileRepo(), “FileRepo”, typeof(IAttachmentRepo));
然后
var service = Locator.Current.GetService(typeof(IAttachmentRepo), cloud ? "AmazonS3" : "FileSystem");
希望这对你有用!