Mid From PDF SOLID Design Patterns & SOLID

Can Factory pattern help with Dependency Injection? Provide example.

Yes! Factory pattern can complement Dependency Injection (DI) by abstracting complex

object creation logic, especially when the creation involves runtime parameters or complex

setup that DI containers can’t handle easily.

Example: Imagine a service that needs different data repositories based on a runtime

parameter.

public interface IRepository { void Save(); }
public class SqlRepository : IRepository { public void Save() =>

Console.WriteLine("Saving to SQL DB"); }

public class InMemoryRepository : IRepository { public void Save()
=> Console.WriteLine("Saving in Memory"); }
public interface IRepositoryFactory
{

IRepository CreateRepository(string repoType);

}
public class RepositoryFactory : IRepositoryFactory
{
public IRepository CreateRepository(string repoType)
{
return repoType.ToLower() switch
{

"sql" => new SqlRepository(),

"memory" => new InMemoryRepository(),

_ => throw new ArgumentException("Invalid repository

type")

};

}
}

// Consumer class with DI

public class Service
{
private readonly IRepositoryFactory _repositoryFactory;
public Service(IRepositoryFactory repositoryFactory)
{
_repositoryFactory = repositoryFactory;
}
public void SaveData(string repoType)
{
var repo = _repositoryFactory.CreateRepository(repoType);

repo.Save();

}
}

Here, DI injects the IRepositoryFactory while the factory manages object creation

based on runtime input. This promotes loose coupling and flexibility.

Strategy Design Pattern

More from Design Patterns in C#

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details