【发布时间】:2015-04-04 00:14:46
【问题描述】:
我在 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);
}
}
但我不是很喜欢这样 :-( 我的设计不好?应该使用依赖注入而不是构造器注入?或者另一个 contrainer 可以做到这一点?
【问题讨论】:
标签: c# .net xamarin inversion-of-control ioc-container