0

I use unity container in my WinForms application and register interfaces and classes. but when open other forms it's not working for fetching data. It's just working for form1. How to resolve all forms?

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        RegisterType(new UnityContainer());
    }

    public static void RegisterType(IUnityContainer container)
    {
        container.RegisterType<IBlogRepository, BlogRepository>();
        container.RegisterType<IPostRepository, PostRepository>();

        Application.Run(container.Resolve<Form1>());
    }
}

This is constructor injection in form1():

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private readonly IBlogRepository _blogRepository;

    public Form1(IBlogRepository blogRepository) : this()
    {
        _blogRepository = blogRepository;
    }

}

and this is constructor injection in formAddUpdate():

public partial class FormAddUpdate : Form
{
    public FormAddUpdate()
    {
        InitializeComponent();
    }

    private readonly IBlogRepository _blogRepository;
    private readonly IPostRepository _postRepository;

    public FormAddUpdate(IBlogRepository blogRepository, IPostRepository postRepository) : this()
    {
        _blogRepository = blogRepository;
        _postRepository = postRepository;
    }

}

now when the run application I can retrieve data from from1 but when switch to add/update form, it returns error: {"Object reference not set to an instance of an object."}

How to resolve all forms in my application?

Jamal Kaksouri
  • 1,684
  • 15
  • 22

1 Answers1

1

If you look at your code, you resolve exactly one type (Form1) from your container. After that, poor container dies.

    RegisterType(new UnityContainer());
}

public static void RegisterType(IUnityContainer container)
{
    container.RegisterType<IBlogRepository, BlogRepository>();
    container.RegisterType<IPostRepository, PostRepository>();

    Application.Run(container.Resolve<Form1>());
}

When you create another container somewhere else to resolve, say, Form2 it knows nothing of the registrations made with the first container, so it can resolve neither BlogRepository nor PostRepository.

So the solution is to keep the one and only container around, the one that you do all registrations with. And use that one to do all your resolving, preferentially not by passing the container around or referencing a static service locator, but instead resolve just one root object and inject factories that do all the resolving needed.

Haukinger
  • 10,420
  • 2
  • 15
  • 28