我在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);
}
}
但我真的不喜欢这样:-(我的设计不好?应该使用dependecy注射而不是construktor注射?或者另一个反对者可以这样做吗?
答案 0 :(得分:1)
使用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