C
C#2y ago
Dasic

❔ How to use abstract factories with DI properly?

Everything works fine till the constructors of the realizations are the same. However, I have a sort of dilemma when the constructors are different. Is it okay or maybe there is an architecture issue? Here is the code:
public class CategoryViewFactory : ICategoryViewFactory
{
private readonly ActiveProgressions _activeProgressions;

public CategoryViewFactory(ActiveProgressions activeProgressions)
{
_activeProgressions = activeProgressions;
}

public ICategoryView? Create(CategoryType type, Category category)
{
return type switch
{
CategoryType.Category => new CategoryView(category),
CategoryType.Subcategory => new SubcategoryView(category, _activeProgressions),
_ => null
};
}
}
public class CategoryViewFactory : ICategoryViewFactory
{
private readonly ActiveProgressions _activeProgressions;

public CategoryViewFactory(ActiveProgressions activeProgressions)
{
_activeProgressions = activeProgressions;
}

public ICategoryView? Create(CategoryType type, Category category)
{
return type switch
{
CategoryType.Category => new CategoryView(category),
CategoryType.Subcategory => new SubcategoryView(category, _activeProgressions),
_ => null
};
}
}
ActiveProgression is a singleton service which I inject using the container. Is it okay? And what I should do if, for instance, ActiveProgression is a transient service? How can I create SubcategoryView in this case? Are there any experts in DI?
2 Replies
Cracker
Cracker2y ago
If you want to inject transient service to singleton service, you can use IServiceProvider. Once you inject IServiceProvider to your singleton service, you can instantiate your transient service with using(var scope = _serviceProvider.CreateScope()){ scope.ServiceProvider.GetRequiredService<ActiveProgressions>() }
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server