Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decor with transient servive and delegate. Could not find a parameterless constructor #19

Closed
robertgm opened this issue Jun 27, 2024 · 1 comment

Comments

@robertgm
Copy link

robertgm commented Jun 27, 2024

Cannot get service inside Transient registration of service.
Project on Git with sample: DecorTransientDelegateBug

Class with Decor attribute:

public class ServiceBLL : IServiceBLL
{
    private readonly IServiceDependencyBLL serviceDependencyBLL;

    public ServiceBLL(IServiceDependencyBLL serviceDependencyBLL)
    {
        this.serviceDependencyBLL = serviceDependencyBLL;
    }

    [Decorate(typeof(CacheDecorator))]
    public string GetValueB()
    {
        return "dependency" + this.serviceDependencyBLL.GetValueA();
    }
}

Service registration:

builder.Services.AddControllers();

builder.Services.AddDecor();
builder.Services.AddSingleton<CacheDecorator>();
builder.Services.AddSingleton<IServiceDependencyBLL, ServiceDependencyBLL >().Decorated();
builder.Services.AddSingleton<ServiceBLL>().Decorated();

builder.Services.AddTransient<Func<string, IServiceBLL>>(serviceProvider => account => {
    switch (account)
    {
        case "countryA":
            return serviceProvider.GetService<ServiceBLL>(); // error
        default:
            throw new Exception("Country does not exist.");
    }
});

When application calls serviceProvider.GetService<ServiceBLL>(); it get error:

 Castle.DynamicProxy.InvalidProxyConstructorArgumentsException: 'Can not instantiate proxy of class: DecorTransientDelegateBug.BLL.ServiceBLL.
Could not find a parameterless constructor.'

I need to have constructor with parameter because I need to use other service that have to be injected in ServiceBLL class.

@lawrence-laz
Copy link
Owner

Decorating concrete types requires them to have a parameterless constructor. This is a limitation of the Castle Core library (discussed here castleproject/Core#532).

As a pretty simple workaround you can register ServiceBLL as an interface, which will not require a parameterless constructor:
image

Closing as a duplicate of #4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants