What is the best way to handle a situation where you're using IoC but there is a static method in it along with the other methods like the following:
public partial class ShoppingCart
{
private IDatabaseFactory _storeDB;
public ShoppingCart(IDatabaseFactory storeDB)
{
_storeDB = storeDB;
}
private string ShoppingCartId { get; set; }
public static ShoppingCart GetCart(HttpContextBase context)
{
var cart = new ShoppingCart(WHATGOESHERE?);
cart.ShoppingCartId = cart.GetCartId(context);
return cart;
}
public int OtherMethod()
{
...
}
}
The static GetCart method is an Ambient Context. It's a bad idea, especially to have such a method at the level of your domain model. Try refactoring it to an abstract factory:
public interface IShoppingCartFactory
{
ShoppingCart GetCartForCurrentUser();
}
You can inject the IShoppingCartFactory in services that need it (but not in your entities, it's better to keep your entities clean). Now you can define an implementation and register it in your IoC configuration. Here's an example of such an implementation:
public class HttpShoppingCartFactory : IShoppingCartFactory
{
private readonly IShoppingUnitOfWorkFactory uowFactory;
public HttpShoppingCartFactory(
IShoppingUnitOfWorkFactory uowFactory)
{
this.uowFactory = uowFactory;
}
public ShoppingCart GetCartForCurrentUser()
{
int userId = (int)HttpContext.Current.Session["userId"];
using (var unitOfWork = this.uowFactory.CreateNew())
{
return unitOfWork.ShoppingCards
.FirstOrDefault(c => c.User.Id == userId);
}
}
}
It would be even better to separate the getting the user context from the shopping card factory. For instance, you yould inject a IUserContextFactory in the shopping card factory, making it independant on ASP.NET.
IMO you should refactor it, making it to look like this:
public class ShoppingCartService {
private readonly IDatabaseFactory _storeDB;
public ShoppingCartService(IDatabaseFactory storeDB) {
_storeDB = storeDB
}
public ShoppingCart GetCart(IdType cartId)
{
var cart = new ShoppingCart(_storeDB);
cart.ShoppingCartId = cartId;
return cart;
}
}
public partial class ShoppingCart
{
private IDatabaseFactory _storeDB;
public ShoppingCart(IDatabaseFactory storeDB)
{
_storeDB = storeDB;
}
private string ShoppingCartId { get; set; }
public int OtherMethod()
{
...
}
}
This way, you are moving responsibility to get the current shopping cart from a static method to a service class you can inject in the presentation layer.
Related
Good day. I have a problem of understanding the Dependency Injection.
So what exactly do I need is to have access from child objects to parent objects.
For example, I have my MainProgram object. This object creates another object, another object create 3-d objects and so on. Let's stop on child object #5
This child needs to have a reference to object #1.
I don't understand how to do this in a better way. But then I started to search and find something called Dependency Injection.
I really hope that this thing is the right answer for my issue (If not, please tell).
So here in my problem and example.
I'm trying to create a WEB API for one of my services. Using ASP .NET Core 6
First, I created a simple class that will be MainProgram, when Server will receive POST request with needed data, it will launch some working in multi-threading.
public class MainProgram
{
public int MaxThreads { get; set; }
public int OrderCounter { get; set; }
public AdjustableSemaphore Semaphore { get; set; }
public MainProgram(int maxThreads)
{
MaxThreads = maxThreads;
Semaphore = new AdjustableSemaphore(MaxThreads);
}
public async Task StartOperation(IApiOperation operation)
{
try
{
operation.Prepare();
operation.Start();
while (!operation.IsReady())
{
await Task.Delay(500);
}
operation.Finish();
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.ResetColor();
}
}
public string OperationStatus(IApiOperation operation)
{
return operation.ShowDetails();
}
}
Then I added this class to Program.cs for Dependency.
builder.Services.AddSingleton(program => new MainProgram(1000));
I made a Constructor for my Controller as it was in the example I read and all worked great.
Controller create instance of MainProgram by its own.
[ApiController]
[Route("/")]
public class ApiController : ControllerBase
{
private MainProgram _mainProgram;
public ApiController(MainProgram mainProgram)
{
_mainProgram = mainProgram;
}
[HttpPost]
[Route("test")]
public string Get()
{
TestOperation to = new TestOperation(_mainProgram);
new Thread(() =>
{
var project = _mainProgram.StartOperation(to);
}).Start();
return $"Started task #{to.Id}";
}
}
The problems that I have are in this line
TestOperation to = new TestOperation(_mainProgram);
This TestOperation also has a Dependency from MainProgram. I understand that I can pass my private _mainProgram in it.
But let's pretend that TestOperation also has a child, and this child also has a child, and only the third one needs a link to MainProgram.
I thought that's where Dependency Injection helps.
Main Question is
How can I create objects that have a constructor with dependency for MainProgram,
If I cannot write new TestOperation(WITHOUT ATTRIBUTE)? It will be a syntax error.
I think you'd avoid the cycle of dependency;
If you couldn't avoid it ,you could try to inject the IServiceProvider into your services,and get the target service with provider.GetService() method,and you could try to create a Parameterservice or Static class to hold the parameter you need,
I tried as below :
Services:
interface IA {int methodA();}
interface IB { int methodB(); }
interface IC { int methodC(); }
interface IParameterService { }
public class ParameterService: IParameterService
{
public int APara;
public int BPara;
public ParameterService(int para)
{
APara = para+1;
}
}
public class A : IA
{
private readonly IServiceProvider _provider;
private readonly int Id;
public A(IServiceProvider provider)
{
_provider = provider;
Id = (provider.GetService(typeof(IParameterService)) as ParameterService).APara;
}
public int methodA()
{
return Id+1;
}
}
public class B : IB
{
private readonly IServiceProvider _provider;
public B(IServiceProvider provider)
{
_provider = provider;
}
public int methodB()
{
return (_provider.GetService(typeof(IA)) as A).methodA();
}
}
public class C : IC
{
private readonly IServiceProvider _provider;
public C(IServiceProvider provider)
{
_provider = provider;
}
public int methodC()
{
return (_provider.GetService(typeof(IB)) as B).methodB();
}
}
In startup:
services.AddTransient<IParameterService>(x => new ParameterService(1));
services.AddTransient<IA,A>();
services.AddTransient<IB,B>();
services.AddTransient<IC, C>();
in controller:
private readonly A _A;
private readonly C _C;
public SomeController(IServiceProvider provider)
{
_A = (A)provider.GetService(typeof(IA));
_C=(C)provider.GetService(typeof(IC));
}
Result:
I am creating a RESTful api in Net 5, according to the instructions I must create repositories and services that make use of them. The logic must be in the services.
The Services I have are:
SubGroupService
GroupsService
The problem I have is that I generated a circular reference since in GroupsService I need a method of SubGroupsService and SubGroupsService i need a method of GroupsService .
Injecting the GroupsService service into SubGroupsService there is no problem, but injecting SubGroupsService into GroupsService generates the circular reference.
Please can you tell me how to solve this type of problem, since I don't have much experience with dependency injection.
SubGroupService
public class SubGroupService: ISubGroupService
{
private readonly ISubGroupRepository _SubGroupRepository;
private readonly IGroupService _GroupService;
public SubGroupService(
ISubGroupRepository SubGroupRepository,
IGroupService GroupService
{
_SubGroupRepository = SubGroupRepository;
_GroupService = GroupService;
}
public async Task InsertSubGroupService(Subgroup subgroup)
{
var group = await _GroupService.GetGroupService(subgroup.idgroup);
if (group != null)
{
await _SubGroupRepository.InsertSubGroupRepository(subgroup);
}
else
{
throw new BusinessException("This group not exists");
}
}
public async Task<Subgroups> GetSubGroupService(int idgroup)
{
return await _SubGroupRepository.GetSubGroupRepository(idgroup);
}
}
Group Service
public class GroupService : IGroupService
{
private readonly ISubGroupService _SubGroupService;
private readonly IGroupRepository _GroupRepository;
public GroupService(
ISubGroupService SubGroupService,
IGroupRepository GroupRepository)
{
_SubGroupService = SubGroupService;
_GroupRepository = GroupRepository;
}
public async Task<bool> DeleteGroupService(int Idgroup)
{
var existsSubGroup = await _SubGroupRepository(Idgroup);
if(existsSubGroup == null)
{
return await _GroupRepository.DeleteGroupRepository(Idgroup);
}
}
public async Task<Groups> GetGroupService(int Idgroup)
{
return await _GroupRepository.GetGroupRepository(Idgroup);
}
}
Interfaces:
public interface IGroupService
{
Task<Groups> GetGroupsService(int Idgroup);
Task<bool> DeleteGroupService(int Idgroup);
}
public interface ISubGroupService
{
Task<Subgroups> GetSubGroupService(int idsubgrupo);
Task InsertSubgroupService(Subgroup subgroup);
}
You can't use constructor injection in that case. You can switch to property injection:
public class SubGroupService: ISubGroupService
{
private readonly ISubGroupRepository _SubGroupRepository;
public IGroupService GroupService { get; set; }
public SubGroupService(
ISubGroupRepository SubGroupRepository)
{
_SubGroupRepository = SubGroupRepository;
}
// methods of the class
}
public class GroupService : IGroupService
{
public ISubGroupService SubGroupService {get; set;}
private readonly IGroupRepository _GroupRepository;
public GroupService(
IGroupRepository GroupRepository)
{
_GroupRepository = GroupRepository;
}
// methods of the class
}
You'll have to create the objects like this:
IGroupRepository groupRepository = new GroupRepository();
IGroupService groupService = new GroupService(groupRepository);
ISubGroupService subGroupService = new SubGroupService(groupRepository);
groupService.SubGroupSerivce = subGroupService;
subGroupService.GroupService = groupService;
Of course, creation of the objects is now much more complicated. You might put the creation into a facotry method to avoid errors:
public (IGroupService,ISubGroupService) CreateGroupAndSubGroupService()
{
// code from above
}
And it is also advisable to add null checks, because someone might create the objects without initializing the service correctly.
Dears,
I used Automapper IMappingAction to encapsulate Before and After Map Actions into small reusable classes but i can't make my class work with ASPNET Bolierplate Ioc Castle Windsor
configuration.CreateMap<CustomerDto, Customer>()
.AfterMap<CustomerAction>().ReverseMap();
public class CustomerAction : IMappingAction<CustomerDto, Customer>
{
private readonly IObjectMapper _objectMapper;
public CustomerAction(IObjectMapper objectMapper)
{
_objectMapper = objectMapper;
}
public void Process(CustomerDto customerDto, Customer customer)
{
}
}
when my code get execute, i got exception that my class doesn't have parameterless constructor
https://github.com/aspnetzero/aspnet-zero-core/issues/1587#issuecomment-415617774
Do you try this?
cfg.CreateMap<CustomerDto, Customer>().AfterMap((source, destination) =>
{
var action = IocManager.IocContainer.Resolve<CustomerAction>();
action.Process(source, destination);
}).ReverseMap();
public class CustomerAction : IMappingAction<CustomerDto, Customer>, ITransientDependency
{
private readonly IObjectMapper _objectMapper;
public CustomerAction(IObjectMapper objectMapper)
{
_objectMapper = objectMapper;
}
public void Process(CustomerDto customerDto, Customer customer)
{
}
}
As i am learning through design pattern concept and also wanted to implement the payment modules in my project using the proper design pattern. So for that I have created some sample code.
Currently I have two concrete implementation for the payment PayPal and Credit Card. But the concrete implementation will be added further on the project.
Payment Service
public interface IPaymentService
{
void MakePayment<T>(T type) where T : class;
}
Credit Card and Pay Pal Service
public class CreditCardPayment : IPaymentService
{
public void MakePayment<T>(T type) where T : class
{
var creditCardModel = (CreditCardModel)(object)type;
//Implementation CreditCardPayment
}
}
class PayPalPayment : IPaymentService
{
public void MakePayment<T>(T type) where T : class
{
var payPalModel = (PayPalModel)(object)type;
//Further Implementation will goes here
}
}
Client Code Implementation
var obj = GetPaymentOption(payType);
obj.MakePayment<PayPalModel>(payPalModel);
Get Payment Option
private static IPaymentService GetPaymentOption(PaymentType paymentType)
{
IPaymentService paymentService = null;
switch (paymentType)
{
case PaymentType.PayPalPayment:
paymentService = new PayPalPayment();
break;
case PaymentType.CreditCardPayment:
paymentService = new CreditCardPayment();
break;
default:
break;
}
return paymentService;
}
I thought of implementing this modules using strategy design pattern, and I got deviated from Strategy and ended up doing this way.
Is this a proper way for creating the payment modules. Is there a more better approach of solving this scenario. Is this a design pattern?
Edited:
Client Code:
static void Main(string[] args)
{
PaymentStrategy paymentStrategy = null;
paymentStrategy = new PaymentStrategy(GetPaymentOption((PaymentType)1));
paymentStrategy.Pay<PayPalModel>(new PayPalModel() { UserName = "", Password = "" });
paymentStrategy = new PaymentStrategy(GetPaymentOption((PaymentType)2));
paymentStrategy.Pay<CreditCardModel>(
new CreditCardModel()
{
CardHolderName = "Aakash"
});
Console.ReadLine();
}
Strategy:
public class PaymentStrategy
{
private readonly IPaymentService paymentService;
public PaymentStrategy(IPaymentService paymentService)
{
this.paymentService = paymentService;
}
public void Pay<T>(T type) where T : class
{
paymentService.MakePayment(type);
}
}
Does this update inlines with the Strategy Pattern?
One major drawback of using an abstract factory for this is the fact that it contains a switch case statement. That inherently means if you want to add a payment service, you have to update the code in the factory class. This is a violation of the Open-Closed Principal which states that entities should be open for extension but closed for modification.
Note that using an Enum to switch between payment providers is also problematic for the same reason. This means that the list of services would have to change every time a payment service is added or removed. Even worse, a payment service can be removed from the strategy, but still be an Enum symbol for it even though it isn't valid.
On the other hand, using a strategy pattern doesn't require a switch case statement. As a result, there are no changes to existing classes when you add or remove a payment service. This, and the fact that the number of payment options will likely be capped at a small double-digit number makes the strategy pattern a better fit for this scenario.
Interfaces
// Empty interface just to ensure that we get a compile
// error if we pass a model that does not belong to our
// payment system.
public interface IPaymentModel { }
public interface IPaymentService
{
void MakePayment<T>(T model) where T : IPaymentModel;
bool AppliesTo(Type provider);
}
public interface IPaymentStrategy
{
void MakePayment<T>(T model) where T : IPaymentModel;
}
Models
public class CreditCardModel : IPaymentModel
{
public string CardHolderName { get; set; }
public string CardNumber { get; set; }
public int ExpirtationMonth { get; set; }
public int ExpirationYear { get; set; }
}
public class PayPalModel : IPaymentModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Payment Service Abstraction
Here is an abstract class that is used to hide the ugly details of casting to the concrete model type from the IPaymentService implementations.
public abstract class PaymentService<TModel> : IPaymentService
where TModel : IPaymentModel
{
public virtual bool AppliesTo(Type provider)
{
return typeof(TModel).Equals(provider);
}
public void MakePayment<T>(T model) where T : IPaymentModel
{
MakePayment((TModel)(object)model);
}
protected abstract void MakePayment(TModel model);
}
Payment Service Implementations
public class CreditCardPayment : PaymentService<CreditCardModel>
{
protected override void MakePayment(CreditCardModel model)
{
//Implementation CreditCardPayment
}
}
public class PayPalPayment : PaymentService<PayPalModel>
{
protected override void MakePayment(PayPalModel model)
{
//Implementation PayPalPayment
}
}
Payment Strategy
Here is the class that ties it all together. Its main purpose is to provide the selection functionality of the payment service based on the type of model passed. But unlike other examples here, it loosely couples the IPaymentService implementations so they are not directly referenced here. This means without changing the design, payment providers can be added or removed.
public class PaymentStrategy : IPaymentStrategy
{
private readonly IEnumerable<IPaymentService> paymentServices;
public PaymentStrategy(IEnumerable<IPaymentService> paymentServices)
{
this.paymentServices = paymentServices ?? throw new ArgumentNullException(nameof(paymentServices));
}
public void MakePayment<T>(T model) where T : IPaymentModel
{
GetPaymentService(model).MakePayment(model);
}
private IPaymentService GetPaymentService<T>(T model) where T : IPaymentModel
{
var result = paymentServices.FirstOrDefault(p => p.AppliesTo(model.GetType()));
if (result == null)
{
throw new InvalidOperationException(
$"Payment service for {model.GetType().ToString()} not registered.");
}
return result;
}
}
Usage
// I am showing this in code, but you would normally
// do this with your DI container in your composition
// root, and the instance would be created by injecting
// it somewhere.
var paymentStrategy = new PaymentStrategy(
new IPaymentService[]
{
new CreditCardPayment(), // <-- inject any dependencies here
new PayPalPayment() // <-- inject any dependencies here
});
// Then once it is injected, you simply do this...
var cc = new CreditCardModel() { CardHolderName = "Bob" /* Set other properties... */ };
paymentStrategy.MakePayment(cc);
// Or this...
var pp = new PayPalModel() { UserName = "Bob" /* Set other properties... */ };
paymentStrategy.MakePayment(pp);
Additional References:
Dependency Injection Unity - Conditional Resolving
Factory method with DI and IoC
This is one approach you could take. There's not a lot to go on from your source, and I'd really reconsider having MakePayment a void instead of something like an IPayResult.
public interface IPayModel { } // Worth investigating into common shared methods and properties for this
public interface IPaymentService
{
void MakePayment(IPayModel payModel);
}
public interface IPaymentService<T> : IPaymentService where T : IPayModel
{
void MakePayment(T payModel); // Void here? Is the status of the payment saved on the concrete pay model? Why not an IPayResult?
}
public class CreditCardModel : IPayModel
{
public string CardHolderName { get; set; }
}
public class PayPalModel : IPayModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
public class CreditCardPayment : IPaymentService<CreditCardModel>
{
public void MakePayment(CreditCardModel payModel)
{
//Implmentation CreditCardPayment
}
void IPaymentService.MakePayment(IPayModel payModel)
{
MakePayment(payModel as CreditCardModel);
}
}
public class PayPalPayment : IPaymentService<PayPalModel>
{
public void MakePayment(PayPalModel payModel)
{
//Implmentation PayPalPayment
}
void IPaymentService.MakePayment(IPayModel payModel)
{
MakePayment(payModel as PayPalModel);
}
}
public enum PaymentType
{
PayPalPayment = 1,
CreditCardPayment = 2
}
So following your implementation approach, it could look something like:
static class Program
{
static void Main(object[] args)
{
IPaymentService paymentStrategy = null;
paymentStrategy = GetPaymentOption((PaymentType)1);
paymentStrategy.MakePayment(new PayPalModel { UserName = "", Password = "" });
paymentStrategy = GetPaymentOption((PaymentType)2);
paymentStrategy.MakePayment(new CreditCardModel { CardHolderName = "Aakash" });
Console.ReadLine();
}
private static IPaymentService GetPaymentOption(PaymentType paymentType)
{
switch (paymentType)
{
case PaymentType.PayPalPayment:
return new PayPalPayment();
case PaymentType.CreditCardPayment:
return new CreditCardPayment();
default:
throw new NotSupportedException($"Payment Type '{paymentType.ToString()}' Not Supported");
}
}
}
I also think for a strategy/factory pattern approach, manually creating an IPayModel type doesn't make much sense. Therefore you could expand the IPaymentService as an IPayModel factory:
public interface IPaymentService
{
IPayModel CreatePayModel();
void MakePayment(IPayModel payModel);
}
public interface IPaymentService<T> : IPaymentService where T : IPayModel
{
new T CreatePayModel();
void MakePayment(T payModel);
}
public class CreditCardPayment : IPaymentService<CreditCardModel>
{
public CreditCardModel CreatePayModel()
{
return new CreditCardModel();
}
public void MakePayment(CreditCardModel payModel)
{
//Implmentation CreditCardPayment
}
IPayModel IPaymentService.CreatePayModel()
{
return CreatePayModel();
}
void IPaymentService.MakePayment(IPayModel payModel)
{
MakePayment(payModel as CreditCardModel);
}
}
Usage would then be:
IPaymentService paymentStrategy = null;
paymentStrategy = GetPaymentOption((PaymentType)1);
var payModel = (PayPalModel)paymentStrategy.CreatePayModel();
payModel.UserName = "";
payModel.Password = "";
paymentStrategy.MakePayment(payModel);
Your code is basically using the factory pattern. This is a good way to handle more than one method of payment
http://www.dotnettricks.com/learn/designpatterns/factory-method-design-pattern-dotnet
We've improved the performance of our API's adding services without state to .SingleInstance() , but I've a question, regarding the demo code attached,
The IBusAppService that we are using on the controller is set to SingleInstance(), but inside the BusAppService, we are using more Interfaces, for example ( IBusRepository or IBusDomainService )
So the question is, in order to increase the performnace, should we set all interfaces to SingleInstance() inside the IBusAppService or the performance is the same because they are inside a SingleInstance??
I'll attach here some code with the workflow :
The ApiController:
public class BusApiController : ApiController
{
private readonly IBusAppService _iBusAppService;
private readonly IBusMapper _iBusMapper;
public BusApiController(IBusAppService iBusAppService,
IBusMapper iBusMapper)
{
_iBusAppService = iBusAppService;
_iBusMapper = iBusMapper;
}
[HttpGet]
public BusResponse Get(long id)
{
var bus = _iBusAppService.Get(id);
var busResponse = _iBusMapper.Convert(bus);
return busResponse;
}
}
public class BusResponse {
public long Id { get; set; }
}
public interface IBusMapper
{
BusResponse Convert(Bus bus);
}
public class BusMapper : IBusMapper
{
public BusResponse Convert(Bus bus)
{
if (bus == null) return null;
var result = new BusResponse{Id = bus.Id};
return result;
}
}
builder.RegisterType<BusAppService>().As<IBusAppService>().SingleInstance();
builder.RegisterType<BusMapper>().As<IBusMapper>().SingleInstance();
The ApplicationService
public interface IBusAppService
{
Bus Get(long id);
}
public class BusAppService : IBusAppService
{
private readonly IBusRepository _iBusRepository;
private readonly IBusDomainService _iBusDomainService;
public BusAppService(IBusRepository iBusRepository, IBusDomainService iBusDomainService )
{
_iBusRepository = iBusRepository;
_iBusDomainService = iBusDomainService;
}
public Bus Get(long id)
{
var bus = this._iBusRepository.Get(id);
var busTax = this._iBusDomainService.CalculateTax(bus);
var result = bus;
return result;
}
}
Anything consumed by a single instance service will end up being single instance due to captive dependencies. You could change them to be single instance, too, but it won't necessarily change the performance related to instantiation cost that you see now.