2015-04-04 46 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