I'm using vNext implementation of DI. How to pass parameters to constructor? For example, i have class:
public class RedisCacheProvider : ICacheProvider { private readonly string _connectionString; public RedisCacheProvider(string connectionString) { _connectionString = connectionString; } //interface methods implementation... }
And service register:
services.AddSingleton<ICacheProvider, RedisCacheProvider>();
How to pass parameter to constructor of RedisCacheProvider class? For example for Autofac:
builder.RegisterType<RedisCacheProvider>() .As<ICacheProvider>() .WithParameter("connectionString", "myPrettyLocalhost:6379");
The parameters of influence are injection speed 71.07%, melting temperature 23.31% and holding pressure 5.62%, respectively. The compressive strength of the product was able to withstand a pressure of up to 839 N before the product became plastic.
Constructor injection should be the main way that you do dependency injection. It's simple: A class needs something and thus asks for it before it can even be constructed. By using the guard pattern, you can use the class with confidence, knowing that the field variable storing that dependency will be a valid instance.
Dependency injection (DI) is a technique widely used in programming and well suited to Android development. By following the principles of DI, you lay the groundwork for good app architecture. Implementing dependency injection provides you with the following advantages: Reusability of code.
You can either provide a delegate to manually instantiate your cache provider or directly provide an instance:
services.AddSingleton<ICacheProvider>(provider => new RedisCacheProvider("myPrettyLocalhost:6379")); services.AddSingleton<ICacheProvider>(new RedisCacheProvider("myPrettyLocalhost:6379"));
Please note that the container will not explicitly dispose of manually instantiated types, even if they implement IDisposable. See the ASP.NET Core doc about Disposal of Services for more info.
If the constructur also has dependencies that should be resolved by DI you can use that:
public class RedisCacheProvider : ICacheProvider { private readonly string _connectionString; private readonly IMyInterface _myImplementation; public RedisCacheProvider(string connectionString, IMyInterface myImplementation) { _connectionString = connectionString; _myImplementation = myImplementation; } //interface methods implementation... }
Startup.cs:
services.AddSingleton<IMyInterface, MyInterface>(); services.AddSingleton<ICacheProvider>(provider => RedisCacheProvider("myPrettyLocalhost:6379", provider.GetService<IMyInterface>()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With