2016-01-17 28 views
13

Tôi đang sử dụng vNext thực hiện DI. Làm thế nào để truyền tham số cho hàm tạo? Ví dụ, tôi có lớp:ASP.NET 5 phụ thuộc tiêm, tiêm với các thông số

public class RedisCacheProvider : ICacheProvider 
{ 
    private readonly string _connectionString; 

    public RedisCacheProvider(string connectionString) 
    { 
     _connectionString = connectionString; 
    } 
    //interface methods implementation... 
} 

Và dịch vụ đăng ký:

services.AddSingleton<ICacheProvider, RedisCacheProvider>(); 

Làm thế nào để vượt qua tham số để constructor của lớp RedisCacheProvider? Ví dụ cho Autofac:

builder.RegisterType<RedisCacheProvider>() 
     .As<ICacheProvider>() 
     .WithParameter("connectionString", "myPrettyLocalhost:6379"); 

Trả lời

34

Bạn có thể cung cấp một đại biểu tự nhanh chóng cung cấp bộ nhớ cache của bạn hoặc trực tiếp cung cấp một ví dụ:

services.AddSingleton<ICacheProvider>(provider => new RedisCacheProvider("myPrettyLocalhost:6379")); 

services.AddInstance<ICacheProvider>(new RedisCacheProvider("myPrettyLocalhost:6379")); 
+0

Làm thế nào bạn sẽ làm điều đó nếu tham số để xây dựng là một biến loại DbContext. Ví dụ: 'PublicServiceService: IStateService { riêng tư BloggingContext _context; StateService công khai (BloggingText context) { _context = context; } công khai IEnumerable Danh sách() { return _context.States.ToList(); } } ' – nam

+0

@nam hãy xem xét điều này. nó giải thích cách thêm một dịch vụ phạm vi. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection – ArcadeRenegade

Các vấn đề liên quan