1
我在Xamarin项目中使用TinyIoc,如果需要,我可以更改IoC容器。我该如何解决这种情况?TinyIoC注入模型到类构造函数
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);
}
}
但我真的不喜欢这种:-(我有一个不好的设计应dependecy注射代替construktor注射使用或?另一个contrainer能做到这一点