Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create objects on demand in C#

Tags:

c#

I am currently optimizing MVC application, there are objects creating in Controller Constructor. Something like this

private readonly IUnitOfWork _unitOfWork;
private readonly GenericRepository<User> _user;
private readonly GenericRepository<UserDevice> _userDevice;
public UsersController()
{
    _unitOfWork = new UnitOfWork();
    _user = new GenericRepository<User>(_unitOfWork);
    _userDevice = new GenericRepository<UserDevice>(_unitOfWork);
}

This is simple example but actually there are a lot more objects creating in Controller Constructor, even there need only one object in function but other objects are creating as well. I want to implement a pattern where objects should create only on when needed.

One thing is in my mind to use Abstract Factory Pattern where all objects should create but I have no idea how to implement. You guys can suggest any other solution for the problem, using pattern is just my thought. Thanks

Edit
On demand means using object in a method, like I need only _user object then why is there _userDevice creating?

like image 911
Ali Shahbaz Avatar asked May 26 '26 06:05

Ali Shahbaz


1 Answers

Lazy<T> seems to be exactly what you are looking for.

private readonly Lazy<IUnitOfWork> _lazyUnitOfWork;

public UsersController()
{
    _layzUnitOfWork = new Lazy<IUnitOfWork>(() => new UnitOfWork());
}

// Instantiates the unit of work on first use
private IUnitOfWork _unitOfWork { get { return _lazyUnitOfWork.Value; } }
like image 147
Heinzi Avatar answered May 30 '26 10:05

Heinzi