我知道你在說什麼!你將做出一種通用化來減少代碼重複(我在跳)。就像你使用.net框架一樣,我不得不說默認情況下它不支持面向方面的編程,讓你在各種情況下表現不同。例如看看這段代碼:
public class BlogService : IBlogService
{
private readonly IBlogRepository _blogRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger _logger;
public BlogService(
IBlogRepository blogRepository,
IUnitOfWork unitOfWork,
ILogger logger)
{
_blogRepository = blogRepository;
_unitOfWork = unitOfWork;
_logger = logger;
}
public GetAllBlogPostResponse GetAllBlogPost(GetAllBlogPostRequest request)
{
var response = new GetAllBlogPostResponse();
try
{
var blogPosts = _blogRepository.GetAll();
if (blogPosts != null)
{
response.BlogPostViewModel = blogPosts.ConvertToPostListViewModel();
response.Success = true;
response.MessageType = MessageType.Success;
response.Message = ServiceMessages.GeneralServiceSuccessMessageOnRetrieveInformation;
_logger.Log(string.Format(response.Message));
}
else
{
response.MessageType = MessageType.Info;
response.Message = ServiceMessages.GeneralServiceAlarmMessageOnRetrieveInformation;
_logger.Log(string.Format(response.Message));
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = ServiceMessages.GeneralServiceAlarmMessageOnRetrieveInformation;
_logger.Log(string.Format(response.Message));
_logger.Log(exception.Message);
}
return response;
}
我在每個服務種類我的應用程序的注入IBlogRepository,IUnitOfWrork和ILogger(log4net的)。而不是說我在每個捕獲聲明中都有類似的迴應和通用信息。一旦我想進行一種泛化,而不是重新實現每個服務類中的類似代碼,但是在這種情況下進行泛化將會更具成本效益和困難。雖然它是如此重要的是不要重複在某些情況下的代碼,例如我有這個BaseController並從中獲得我所有的控制器來自:
public class BaseController : Controller
{
private readonly ICookieStorageService _cookieStorageService;
private readonly ILanguageService _languageService;
public BaseController(ICookieStorageService cookieStorageService,ILanguageService languageService)
{
_cookieStorageService = cookieStorageService;
_languageService = languageService;
}
}
所以我不需要在我的控制器創建cookieStorageService和languageService每一次,因爲我已經實施了一次。
相關:https://stackoverflow.com/questions/5646820/logger-wrapper-best-practice – Steven
考慮將您的橫切關注點(日誌記錄)移到一個裝飾器類中,然後您將它註冊到Ninject。併爲您的第三方依賴使用代理類。 –
是的,那個討論就是我期待的事情。對不起,它沒有出現在我的搜索。 – user2403744