如何在非MVC应用程序中访问IUnityContainer?

时间:2016-04-11 05:17:38

标签: c# unity-container

我知道ASP.NET MVC有DependencyResolver。如何在非MVC应用程序中对IUnityContainer进行类似的应用程序范围访问?使用公共静态类是无稽之谈。这是我的用例:

public partial class App : Application
{
    public App()
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterInstance(new MyClass());
    }
}
public class MainViewModel
{
    public MainViewModel()
    {
       IUnityContainer container = ???
       if (container.IsRegistered<MyClass>())
           DoSomething();
    }
}

2 个答案:

答案 0 :(得分:1)

如果您正在寻找适用于大多数应用程序的解决方案,您可以在最高级别注册该组件,然后解决它。只要您解析实例,Unity就会解析依赖关系(例如IUnityContainer)。

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Registering dependencies ...");

        var container = new UnityContainer();
        container.RegisterType<ProgramStarter, ProgramStarter>();

        // Do other registrations.
        var program = container.Resolve<ProgramStarter>();

        // Since ProgramStarter was resolved using Unity it will also resolve the container.
        program.Run();
    }
}

public class ProgramStarter
{
    public ProgramStarter(IUnityContainer container)
    {
        // Do something with container.
    }

    public Run()
    {
        // Do stuff.
    }
}

或WPF的示例:

IUnityContainer container = new UnityContainer();
// Do registrations.
var window = container.Resolve<MainWindow>();
window.Show();

MainWindow现在可以解析容器和其他依赖项。

另外,请看一下这个问题:Where to place and configure IoC container in a WPF application?

作为旁注,我通常将我的容器保存为静态实例,并看到很多其他实现都在做同样的事情。当你发现自己无法解决问题时,我觉得使用它很方便。

public static class IocContainer
{
    private static readonly Lazy<IUnityContainer> Container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        // Possibly do registrations here as well...
        return container;
    });

    public static IUnityContainer Instance
    {
        get { return Container.Value; }
    }
}

答案 1 :(得分:0)

我不认为除了你指定的方法之外还有其他方法可以为非MVC应用程序实现IOC和DI。如果还有一种方式,那么任何建议都会受到赞赏。