7

ASP.NET 5 MVC uygulamam için bir yetkilendirme kuralı/ilkesi oluşturuyorum. Bunu yaratmak basit ve kolay bir işti ve işe yarıyordu (temel testlerimle). Ancak, şimdi veri içeriğimi gereksinime göre almam gerekiyor.Yetkilendirmede Bağımlılık EnjeksiyonuOptions

DbContext uygulayan bir MyContext nesnesi alan IAuthorizationRequirement uygulamasında bir oluşturucu oluşturdum.

IAuthorizationRequirement'i Startup.cs dosyamda kaydediyorum. Benim kural çalıştırıldığında

services.Configure<AuthorizationOptions>(options => 
    { 
     options.AddPolicy("AllowProfileManagement", policy => policy.Requirements.Add(
      new AllowProfileManagementRequirement(new MyRepository(new MyContext())))); 
    }); 

yazık ki, MyContext (öteye Startup.cs yukarı) şöyle kullanılan bağlantı dizeleri habersiz: (

services.AddEntityFramework() 
    .AddSqlServer() 
    .AddDbContext<MemorialContext>(options => 
     options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); 

başka türlü bu tip DI kullanıyorum ve çalışıyor).

services.AddTransient<MyRepository>(
     provider => new MyRepository(provider.GetRequiredService<MyContext>())); 

Ben ne yapıyorum doğru değil biliyorum ama DI tüm öğeler arasında kaldıraçlı ediliyor, böylece bu hakkı nasıl görmüyorum.

cevap

5

Her zaman böyle çalışır. Soruyu gönderin ve cevap kısa bir süre sonra gelir. İşte soruma rastlayanlar için.

services.Configure<AuthorizationOptions>(options => 
    { 
     options.AddPolicy("AllowProfileManagement", policy => policy.Requirements.Add(
      services.BuildServiceProvider().GetRequiredService< AllowProfileManagementRequirement>())); 
    }); 
İlgili konular