AOP for C# dotnet core 2.0, access method parameter values before method body runs

这一生的挚爱 提交于 2019-12-04 17:06:40

Look into CQS, decorators and SimpleInjector. If you promote methods to classes, you can have the class dedicated to one thing (SOLID). Then you can add cross cutting concerns on decorators that will have the same interface as the implementation, but they essential chain the calls. if validation decorator fails, then your main logic won't ever be called. You can even add all exception handling here and any logging or retry logic or caching.

Edit

Sorry, was on mobile before! :)

For an example, I'll use your method here. Normally with CQS, you'd have a generic interface for all your queries (read-only) and commands (change state). That way, all your logic ends up going through a IQueryHandler or ICommandHandler so you can add cross cutting concerns to ALL your logic all at once. However, I'll make an example specific to your question.

public interface ISaveComponent
{
    Component SaveComponent(Component componentToSave);
}

public class SaveComponent : ISaveComponent
{
    public Component SaveComponent(Component componentToSave)
    {
        // Do your work here
    }
}

public class SaveComponentValidation : ISaveComponent
{
    private readonly ISaveComponent _saveComponent;

    public SaveComponentValidation(ISaveComponent saveCompnent)
    {
        _saveComponent = saveCompnent;
    }

    public Component SaveComponent(Component componentToSave)
    {
        // Do Validation here
        return _saveComponent.SaveComponent(componentToSave);
    }
}

If you let SimpleInjector (IoC/DI) handle the decorations for you, then you just have to register them in one line of code like this:

 container.RegisterDecorator(typeof(ISaveComponent), typeof(SaveComponentValidation));

Otherwise, you would have to manually create them like this:

public class Program
{
    public static void Main()
    {
        ISaveComponent handler = new SaveComponentValidation(new SaveComponent());
        handler.SaveComponent(new Component());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!