Answer the question
In order to leave comments, you need to log in
Proper use of UnitOfWork in services?
Good day!
The system is designed on N-Layer architecture:
namespace MyApp.BLL.Services
{
public class MyService
{
private UnitOfWork _uow { get; set; }
public MyService()
{
_uow = new UnitOfWork();
}
public List<SomeDTO> SomeGetMethod()
{
IEnumerable<Entity> entities = _uow.SomeRepository.Get(x => x.Id==1);
...
return ...
}
public void SomeSetMethod(int value)
{
_uow.SomeRepository.Insert(new Entity { Value = value });
_uow.Commit(); // SaveChanges();
}
public Dispose()
{
_uow.Dispose();
}
}
}
namespace MyApp.BLL.Services
{
public class MyService
{
public List<SomeDTO> SomeGetMethod()
{
using(UnitOfWork uow = new UnitOfWork())
{
IEnumerable<Entity> entities = uow.SomeRepository.Get(x => x.Id==1);
}
....
return ...
}
public void SomeSetMethod(int value)
{
using(UnitOfWork uow = new UnitOfWork())
{
uow.SomeRepository.Insert(new Entity { Value = value });
uow.Commit(); // SaveChanges();
}
}
}
}
public interface IMessagesService
{
void Send(int userFrom, int userTo, string message);
// other methods...
}
public class MessageService
{
public void Send(int userFrom, int userTo, string message)
{
// some logic here
}
}
public interface ISomeService
{
void SomeMethod(int somevalue);
}
public class SomeService: ISomeService
{
public void SomeMethod(int somevalue)
{
// some logic here
// после необходимо отправить сообщение
messageService = new MessageService();
messageService.Send(1, 2, "some text");
}
}
Answer the question
In order to leave comments, you need to log in
Good afternoon!
On the first question, I would prefer using, because you can accidentally forget to explicitly call Dispose. And using, as you know, will call it itself.
But on the second question - I'm afraid I can not suggest the only correct solution. I myself somehow encountered such a problem, and thought for a long time how to solve it. Especially when using IoC containers. On one of the projects of the company where I am currently working, the following approach is used: a singleton is created, in which interfaces are listed as properties, for example:
public sealed class Endpoint
{
...
// Закрытый конструктор
private Endpoint()
{
Initialization();
}
...
// Реализация синглтона
public static Endpoint Instance
{
get
{
if (_instance == null)
{
lock (InstanceLocker)
{
if (_instance == null)
_instance = new Endpoint();
}
}
return _instance;
}
}
...
public IMyService MyService { get; private set; }
public ISomeService SomeService { get; private set; }
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question