How should I use IoC in this part of winform code?

I have a winform application in visual studio 2010. My application does the following

  • Get the list of files that I need to read the data, and then paste it into the database.
  • For each file, read the data and paste it into the database.

So this is the code that I have.

// ******* // *** How should the _repository be Injected?? // ******* var list = _repository.GetFileList(); if (list != null) { int i = 0; foreach(var file in list) { i++; var service = new MyService(i, _repository); service.ParseAndSave(); } } 

So, I was hoping to create a new repository for every service I create.

First, I'm not sure if I should use IoC in this case. I believe that it should be, because then I do not need to tightly associate this winform with the repository.

Secondly, I tried using the Singleton repository, which I donโ€™t want, and can confirm that it kills this code (failure with exception).

Some other notes (which should not affect this question) - Using Entity Framework for ASP.NET 4. - Using StructureMap for IoC

Can someone help please?

UPDATE

Oh, I forgot to mention. When I do not specify the type of life cycle (e.g. Singleton, etc.). my objects that I am trying to save are simply not saved. (i.e. nothing is sent to the database looking at SQL Profiler). If I use Singleton with one file ... it works. A singleton with 2+ files, then the exception / failure due to the (internal EF) Primary key conflicts with the Entity Framework. So if I have to use Singleton, then the problem should be how to set up my EF4 context.

+4
source share
2 answers

You have two main options: Constructor injection (as in the example of Mark Seemann) or True (setter) (where supported by your container, for example Unity)

In the case of winform, you need to either use the Property (setter) injection, which allows you to use the default constructor, or again, as Mark points out, using the form as a simple data visualizer, in which case you should probably consider some kind of Presentation View Model > (note that this link has been further refined and shared)

His work looks at sample code for the MS Patterns and Practices Prism Project for some examples that use the MVP approach with Unity.

0
source

Constructor injection is always a good start

 public MyClass(IRepository repository) { if(repository == null) { throw new ArgumentNullException("repository"); } this.repository = repository; } 

However, in Windows Forms, you are faced with the fact that your Form classes must have default constructors to support development functionality in Visual Studio. You can solve this problem by making sure your forms are nothing more than dumb data visualizers .

0
source

Source: https://habr.com/ru/post/1304565/


All Articles