Suppose I have an interface registered by 3pty library to the default container
// 3pty lib
public interface IFoo {
SayHello();
SayBye();
}
internal sealed class FooInternal : IFoo { ... }
public static WithFoo(this IServiceCollection serviceCollection) {
serviceCollection.AddScoped<IFoo, FooInternal>();
}
And I do want to overwrite the SayBye()
method. I've created a class
class FooProxy : IFoo {
private readonly IFoo baseFoo;
public FooProxy(IFoo baseFoo) {
this.baseFoo = baseFoo;
}
public void SayHello() { baseFoo.SayHello(); }
public void SayBye() { ... }
}
Now the problem I'm facing is how to hook it up to dependency injection. I've tried:
// leads to infinite recursion death
services.AddScoped<IFoo>((sp) => new FooProxy(sp.GetRequiredService<IFoo>()));
And also:
public class FooProxy : IFoo {
private readonly Func<IFoo> baseFoo;
SayHello() { baseFoo().SayHello(); }
}
// leads to object disposed error
services.AddScoped<IFoo>((sp) => new FooProxy(() => sp.GetRequiredService<IFoo>()));
This is something you can achieve using Decorator Pattern.
For this there is one library.
https://github.com/khellang/Scrutor
service.AddScoped<IFoo,FooConcrete>(); // This I believe register by Third Party service.Decorate<IFoo,FooProxy>(); // This is you will add.
Another way which is bit not good.
public interface IFooProxy: IFoo { } public class FooProxy: IFooProxy { public FooProxy(IFoo foo) { } } // Configure Sevices services.AddScoped<IFooProxy,FooProxy>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.