[英]TinyIoC inject model to class constructor
我在xamarin項目中使用TinyIoc,如有必要,我可以更改IoC容器。 我該如何解決這種情況?
internal class Program
{
private static void Main(string[] args)
{
TinyIoC.TinyIoCContainer.Current.Register<IService, Service>();
TinyIoC.TinyIoCContainer.Current.Register<ViewModel>();
Model model; //From database... How I can inject this to my viewmodel?
var viewModel = TinyIoC.TinyIoCContainer.Current.Resolve<ViewModel>();
}
}
public class Model
{
public object Data { get; set; }
}
internal interface IService
{
string SomeMethod(Model model);
}
public class Service : IService
{
public string SomeMethod(Model model)
{
//...
return string.Empty;
}
}
internal class ViewModel
{
private readonly Model model;
private readonly IService service;
public string Name { get; private set; }
public ViewModel(IService service, Model model)
{
this.model = model;
this.service = service;
this.Name = this.service.SomeMethod(this.model);
}
}
我想到的唯一一件事是:
internal class Program
{
private static void Main(string[] args)
{
TinyIoC.TinyIoCContainer.Current.Register<IService, Service>();
TinyIoC.TinyIoCContainer.Current.Register<ViewModel>();
Model model; //From database... How I can inject this to my viewmodel?
var viewModel = TinyIoC.TinyIoCContainer.Current.Resolve<ViewModel>();
viewModel.Initialize(model);
}
}
internal class ViewModel
{
private Model model;
private readonly IService service;
public string Name { get; private set; }
public ViewModel(IService service)
{
this.service = service;
}
public void Initialize(Model model)
{
this.model = model;
this.Name = this.service.SomeMethod(this.model);
}
}
但是我真的不是這樣:-(我的設計不好?應該使用可靠注射代替構造劑注射嗎?或者可以使用其他禁忌葯嗎?
看看Func的重載方法,看看哪種方法最適合,因為我不知道TinyIoC如何處理實際的實現注冊。 這樣的事情可能會起作用:
.Register<ViewModel>(() => new ViewModel(
TinyIoC.TinyIoCContainer.Current.Resolve<IService>(),
model));
或只是傳遞服務的新實例:
.Register<ViewModel>(() => new ViewModel(new Service(), model));
如果TinyIoC不符合要求,則可以查看XLabs.IoC,了解與Xamarin兼容的替代方案: http ://www.nuget.org/packages?q=xlabs.ioc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.