Asp.Net Core RC1 & # 8594; RTM DI changes - removed fromServices

I am using a structural card with RTM AspNet Core 1.0. Apparently they are removed using the FromServices attribute for the properties. This breaks the code below, because now I can not enter ClaimsPrincipal. I am not sure how to make the DI system pick up this property. Do I need to create a custom InputFormatter or something else. It seems like a lot of work to get this work done again.

Startup.cs

public class Startup { public IServiceProvider ConfigureServices(IServiceCollection services) { var container = new Container(); container.Configure(i => { i.For<IHttpContextAccessor>() .Use(new HttpContextAccessor()); i.For<ClaimsPrincipal>() .Use(x => x.GetInstance<IHttpContextAccessor>().HttpContext.User); }); container.Populate(services); return container.GetInstance<IServiceProvider>(); } } 

Model.cs

 public class Model { //[FromServices] <-- worked in RC1 public ClaimsPrincipal Principal { get; set; } public string Value => Principal.Identity.Name; } 

Testcontroller.cs

 public class TestController : Controller { public IActionResult Test(Model model){ return Ok(); } } 
+7
c # dependency-injection asp.net-core structuremap4
source share
1 answer

As far as I know, one of the main reasons why this has been eliminated is related to the confusion about where it works and where not. For example, FromServices was the concept of MVC model binding, and some users tried to use it outside of MVC and found that it did not work.

However, you can create your own model binding attribute to achieve similar behavior.

For example, this works with decoration on a model. NOTE I have not tested wit on a controller property.

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class FromDIAttribute : Attribute, IBindingSourceMetadata { public BindingSource BindingSource { get { return BindingSource.Services; } } } public class Customer { [FromDI] public IFooService FooService { get; set; } public string Name { get; set; } } 

UPDATE :

Found an ad for his removal here: https://github.com/aspnet/Announcements/issues/115

+5
source share

All Articles