【问题标题】:TinyIoC inject model to class constructorTinyIoC 将模型注入类构造函数
【发布时间】: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


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      相关资源
      最近更新 更多