2015-04-04 37 views
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能做到这一点

回答

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