Avatar
0
Nguyen Nam Teacher
Nguyen Nam Teacher
Service trong .net
Chào mọi người. Hiện tại em đang có vấn đề như này nhờ mọi người giải quyết giúp ạ.
  • Yêu cầu chức năng:
    + Sau khi gửi mail sẽ update trạng thái là đã gửi request gửi mail.
    + Sau khi nhận thông báo gửi mail thành công từ webhook của server mail sẽ update trạng thái là gửi mail thành công và tiến hành gửi mail thông báo.
  • Mong muốn:
    + Hiện tại em muốn chia thành 2 service là
    ・ Service gửi mail
    ・ Service update trạng thái mail
    + Code sẽ kiểu như thế này:
    		public class ServiceSendMail : IServiceSendMail {
    			IServiceUpdateStatusMail _b;
    		
    			public ServiceSendMail(IServiceUpdateStatusMail b){
    				_b = b;
    			}
    
    			public void SendMail(){
    				_b.UpdateStatus();
    			}
    		}
    
    		public class ServiceUpdateStatusMail : IServiceUpdateStatusMail{
    			IServiceSendMail _a;
    			
    			public ServiceUpdateStatusMail(IServiceSendMail a){
    				_a = a;
    			}
    
    			public void UpdateStatus(){
    				_a.SendMail();
    			}
    		}
    
  • Vấn đề gặp phải:
    Lỗi stackoverflow exception

  • Cách làm tạm thời:
    + Gộp 2 service vào 1
Mọi người còn cách nào hay ho hơn không ạ. Chỉ giúp em với
Em xin cảm ơn trước ạ.
  • Answer
c# netcore
Remain: 5
1 Answer
Avatar
monkey Enlightened
monkey Enlightened
mediator design pattern
để giải quyết bài toán này nhé:
public interface IServiceSendMail
{
    void SendMail();
}

public interface IServiceUpdateStatusMail
{
    void UpdateStatus();
}

public class MailServiceMediator
{

    IServiceSendMail Sender;
    IServiceUpdateStatusMail StatusUpdater;

    public void SendMail()
    {
        Sender.SendMail();
        StatusUpdater.UpdateStatus();
        Sender.SendMail();
    }
}

public class ServiceSendMail : IServiceSendMail
{
    public void SendMail()
    {
    }
}

public class ServiceUpdateStatusMail : IServiceUpdateStatusMail
{
    public void UpdateStatus()
    {
    }
}
  • 1
  • Reply
Cách này cũng khá giống với việc trong SendMailService không trực tiếp gọi UpdateStatusMailService mà thông qua IServiceProvider để gọi service UpdateStatusMailService.
Code sẽ kiểu như thế này ạ
public class ServiceA : IServiceA {
	IServiceProvider _serviceProvider;
	
	public ServiceA(IServiceProvider serviceProvider){
		_serviceProvider = serviceProvider;
	}
	
	public void DoSomething(){
		_serviceProvider.GetRequiredService().DoSomething();
	}
}

public class ServiceB : IServiceB{
	IServiceProvider _serviceProvider;
	
	public ServiceB(IServiceProvider serviceProvider){
		_serviceProvider = serviceProvider;
	}
	
	public void DoSomething(){
		_serviceProvider.GetRequiredService().DoSomething();
	}
}
 –  Nguyen Nam 1630876802000
Ừ, bản chất nó là mediator design pattern, có thằng còn tạo hẳn 1 thư viện cho C# đó: https://github.com/jbogard/MediatR
 –  monkey 1630879624000