Fork me on GitHub

AspNet5 Changes to [Activate] in beta-5

最近在看AspNet Core相关的文章,其中有个TagHelper,看上善若水的博客“关于TagHelper的那些事”,其中有一句

下面来自上善若水的博客原文:

我们知道ASP.NET 5实现了依赖注入,在TagHelper类中我们也可以通过依赖注入获取更多的系统实例对象,为具体需求所有。我们只需要在TagHelper类中,添加一个相关类型的属性,然后在属性头上添加Activate属性即可自动获取对应实例。比如,获取ViewContext信息,可以在类中添加如下代码:

1 [Activate]
2 public ViewContext ViewContext { get; set; }

这样我们就可以在其他地方,通过属性ViewContext获取当前View的上下文信息。

通过这种方式,你可以获取到更多的系统实例对象,如ActionContextHttpContextHttpRequestHttpResponse、 ViewDataDictionary以及ActionBindingContext等。具体关于依赖注入的介绍见这里

上面来自上善若水的博客原文。

我查了半天资料找不到这个ActivateAttribute的命名空间。后来在bing上搜索找到了下面这篇文章

https://github.com/aspnet/Announcements/issues/28

Activate特性已经在beta-5中改变了

POCO Controller Sample

Before:

1 public class MyController
2 {
3     [Activate]
4     public ActionContext ActionContext { get; set; }
5 
6     [Activate]
7     public HttpContext HttpContext { get; set; }
8 }

 

After:

1 public class MyController
2 {
3     [ActionContext]
4     public ActionContext ActionContext { get; set; }
5 
6     public HttpContext HttpContext => ActionContext.HttpContext
7 }

 

POCO ViewComponent Sample

Before:

1 public class MyViewComponent
2 {
3     [Activate]
4     public IRespository Repository { get; set; }
5 
6     [Activate]
7     public ViewContext ViewContext { get; set; }
8 }

 

After:

 1 public class MyViewComponent
 2 {
 3     public MyViewComponent(IRepository repository)
 4     {
 5         Repository = repository;
 6     }
 7 
 8     public IRespository Repository { get; }
 9 
10     [ViewComponentContext]
11     public ViewComponentContext ViewComponentContext { get; set; }
12 }

 

TagHelper Sample

Before:

 1 public class MyTagHelper : TagHelper
 2 {
 3     [HtmlAttributeNotBound]
 4     [Activate]
 5     public IHtmlEncoder Encoder { get; set; }
 6 
 7     [HtmlAttributeNotBound]
 8     [Activate]
 9     public ViewContext ViewContext { get; set; }
10 }

 

After:

public class MyTagHelper : TagHelper
{
    public MyTagHelper(IHtmlEncoder encoder)
    {
        Encoder = encoder;
    }

    public IHtmlEncoder Encoder { get; }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }
}

上面只是几个例子,要想了解具体情况请参考:https://github.com/aspnet/Announcements

posted @ 2017-04-10 11:12  雪山玉龙  阅读(135)  评论(0编辑  收藏  举报