Building simple plug-ins system for ASP.NET Core(转)
Recently I built plug-ins support to my TemperatureStation IoT solution web site. The code for .NET Core is different from what we have seen on full .NET Framework (application domains etc) but there’s still nothing complex. This blog post describes how to build simple plug-ins support to ASP.NET Core web application.
After some searching in web and some small experimenting I came out with simple solution that covers the following:
- Loading types from assemblies
- Registering types automatically with built-in dependency injection
- Getting instances through built-in dependency injection
The code shown here is also kind of experimental and it is taken from my open-source IoT solution called TemperatureStation.
Calculator plug-ins
TemperatureStation has plug-ins called Calculators. Calculators are classes that can be bound to measurements and when readings are reported then Calculators are run on readings. They provide different calculations like finding freezing point of liquid, estimating the time it takes for liquid to get to freezing point etc.
For calculators there is ICalculator interface shown below.
public interface ICalculator
{
double Calculate(SensorReadings readings, Measurement measurement);
string DisplayValue(double value);
bool ReturnsReading { get; }
void SetParameters(string parameters);
}
Calculators use CalculatorAttribute to define some metadata.
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class CalculatorAttribute : Attribute
{
public CalculatorAttribute()
{
Order = -1;
ShowOnChart = true;
} public string Name { get; set; }
public int Order { get; set; }
public bool ShowOnChart { get; set; }
public string DisplayLabel { get; set; }
}
And here is the example of dummy calculator.
public class DummyCalculator : ICalculator
{
public bool ReturnsReading
{
get { return true; }
} public double Calculate(SensorReadings readings, Measurement measurement)
{
return readings.Readings.First().Reading + 10f;
} public string DisplayValue(double value)
{
return value.ToString();
} public void SetParameters(string parameters)
{
}
}
Finding plug-in types
To detect plug-ins I wrote CalculatorsLoader class. This a static class that creates list of calculator types. Rule is simple: class must implement ICalculator interface and must have CalculatorAttribute. Consider this class as internal matter of application.
public static class CalculatorsLoader
{
private static IList<Type> _calculatorTypes; public static IList<Type> CalculatorTypes
{
get
{
if(_calculatorTypes == null)
{
LoadCalculatorTypes();
} return _calculatorTypes.ToList();
}
} private static void LoadCalculatorTypes()
{
if (_calculatorTypes != null)
{
return;
} var calcs = from a in GetReferencingAssemblies()
from t in a.GetTypes()
where t.GetTypeInfo().GetCustomAttribute<CalculatorAttribute>() != null
&& t.GetTypeInfo().ImplementedInterfaces.Contains(typeof(ICalculator))
select t; _calculatorTypes = calcs.OrderBy(t => t.GetTypeInfo().GetCustomAttribute<CalculatorAttribute>().Order).ToList();
} private static IEnumerable<Assembly> GetReferencingAssemblies()
{
var assemblies = new List<Assembly>();
var dependencies = DependencyContext.Default.RuntimeLibraries; foreach (var library in dependencies)
{
try
{
var assembly = Assembly.Load(new AssemblyName(library.Name));
assemblies.Add(assembly);
}
catch (FileNotFoundException)
{ }
}
return assemblies;
}
}
Automatic registering of plug-in types
To use ASP.NET Core dependency injection I wrote class that provides extension method for IServiceCollection. Dependency injection is needed because Calculators may use constructor injection to access services and database.
public static class CalculatorExtensions
{
public static void AddCalculators(this IServiceCollection services)
{
foreach(var calcType in CalculatorsLoader.CalculatorTypes)
{
services.AddTransient(calcType);
}
}
}
This is how to use AddCalculators extension method in Startup class of web application.
public void ConfigureServices(IServiceCollection services)
{
// ... services.AddMvc(); services.AddSingleton<ICalculatorProvider, CalculatorProvider>();
services.AddCalculators(); // ...
}
When web application starts then ConfigureServices method is called and Calculators are automatically registered.
Plug-in provider
To access calculators I wrote ICalculatorProvider interface and CalculatorProvider class. This class with CalculatorExtensions are the only classes that access CalculatorsLoader directly. All other classes in system use provider to query calcutor types. ICalculatorProvider is introduced to ASP.NET Core dependency injection in application Startup class.
GetCalculators() method uses framework level dependency injection to create instances of ICalculator.
public interface ICalculatorProvider
{
IDictionary<string, ICalculator> GetCalculators();
IEnumerable<string> GetNames();
IEnumerable<Type> GetTypes();
} public class CalculatorProvider : ICalculatorProvider
{
private IServiceProvider _serviceProvider; public CalculatorProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
} public IDictionary<string,ICalculator> GetCalculators()
{
var result = new Dictionary<string, ICalculator>(); foreach(var type in CalculatorsLoader.CalculatorTypes)
{
var calc = (ICalculator)_serviceProvider.GetService(type);
var name = type.GetTypeInfo().GetCustomAttribute<CalculatorAttribute>().Name; result.Add(name, calc);
} return result;
} public IEnumerable<string> GetNames()
{
return CalculatorsLoader.CalculatorTypes
.Select(t => t.GetTypeInfo().GetCustomAttribute<CalculatorAttribute>()?.Name)
.Where(t => !string.IsNullOrWhiteSpace(t));
} public IEnumerable<Type> GetTypes()
{
return CalculatorsLoader.CalculatorTypes;
}
}
Using plug-ins in code
Here is the example about how I use ICalculatorProvider in controller code to output the list of available calculators.
public class DummyController : Controller
{
private ICalculatorProvider _calculatorProvider; public DummyController(ICalculatorProvider calculatorProvider)
{
_calculatorProvider = calculatorProvider;
} public IActionResult GetCalculators()
{
var calculators = _calculatorProvider.GetCalculators();
var output = ""; foreach (var calculator in calculators)
{
output += calculator.Key + "\r\n";
} return Content(output, "text/plain");
}
}
The real usage in my solution is more complex but this example gives the point.
Wrapping up
On .NET Core things work a little bit differently compared to full .NET Framework. Although this solution is not perfect it was still pretty easy to find information and make code work. It was also easy to automatically register plug-in types with ASP.NET Core framework-level dependency injection and come out with simple classes that architecturally fit in to web application. For my IoT system this solution today is good enough to go with.
原文:http://gunnarpeipman.com/2017/01/aspnet-core-plugins/
Building simple plug-ins system for ASP.NET Core(转)的更多相关文章
- User Authentication with Angular and ASP.NET Core
User authentication is a fundamental part of any meaningful application. Unfortunately, implementing ...
- ASP.NET Core 中文文档 第二章 指南(2)用 Visual Studio 和 ASP.NET Core MVC 创建首个 Web API
原文:Building Your First Web API with ASP.NET Core MVC and Visual Studio 作者:Mike Wasson 和 Rick Anderso ...
- 【原生态跨平台:ASP.NET Core 1.0(非Mono)在 Ubuntu 14.04 服务器上一对一的配置实现-篇幅1】
鸡冻人心的2016,微软高产年. build 2016后 各种干货层出不穷. 1 Win10 集成了bash ,实现了纳德拉的成诺,Microsoft Love Linux!!! 2 跨平台 ,收 ...
- ABP 教程文档 1-1 手把手引进门之 ASP.NET Core & Entity Framework Core(官方教程翻译版 版本3.2.5)
本文是ABP官方文档翻译版,翻译基于 3.2.5 版本 官方文档分四部分 一. 教程文档 二.ABP 框架 三.zero 模块 四.其他(中文翻译资源) 本篇是第一部分的第一篇. 第一部分分三篇 1- ...
- 如何使用ASP.NET Core、EF Core、ABP(ASP.NET Boilerplate)创建分层的Web应用程序(第一部分)
本文是为了学习ABP的使用,是翻译ABP官方文档的一篇实战教程,我暂时是优先翻译自己感兴趣或者比较想学习的部分,后续有时间希望能将ABP系列翻译出来,除了自己能学习外,有可能的话希望帮助一些英文阅读能 ...
- Handle Refresh Token Using ASP.NET Core 2.0 And JSON Web Token
来源: https://www.c-sharpcorner.com/article/handle-refresh-token-using-asp-net-core-2-0-and-json-web ...
- ASP.NET Core身份识别
Introduction to Identity 66 of 93 people found this helpful By Pranav Rastogi, Rick Anderson, Tom Dy ...
- ASP.NET Core 认证与授权[4]:JwtBearer认证
在现代Web应用程序中,通常会使用Web, WebApp, NativeApp等多种呈现方式,而后端也由以前的Razor渲染HTML,转变为Stateless的RESTFulAPI,因此,我们需要一种 ...
- 5. abp集成asp.net core
一.前言 参照前篇<4. abp中的asp.net core模块剖析>,首先放张图,这也是asp.net core框架上MVC模块的扩展点 二.abp的mvc对象 AbpAspNetCor ...
随机推荐
- 20155216 实验二 Java面向对象程序设计
实验二:Java面向对象程序设计 实验内容 1.初步掌握单元测试和TDD. 2.理解并掌握面向对象的三要素:封装.继承.多态. 3.初步掌握UML建模. 4.熟悉S.O.L.I.D原则. 5.了解设计 ...
- 20155308&20155316 2017-2018-1 《信息安全系统设计基础》实验三
20155308&20155316 2017-2018-1 <信息安全系统设计基础>实验三 并发程序-1 学习使用Linux命令wc(1) 基于Linux Socket程序设计实现 ...
- 20155336 实验三 敏捷开发与XP实践
20155336 实验三 敏捷开发与XP实践 实验内容 XP基础 XP核心实践 相关工具 实验内容及步骤 (一)编码标准:在IDEA中使用工具(Code->Reformate Code)把代码重 ...
- 简单的Slony-I设置实例 II
磨砺技术珠矶,践行数据之道,追求卓越价值 回到上一级页面: PostgreSQL集群方案相关索引页 回到顶级页面:PostgreSQL索引页 接前面例子, 简单的Slony-I设置实例 这次我 ...
- springboot中maven加入本地jar
一.今天遇到一个问题,在使用springboot打jar的时候出现了本地依赖包打不进去的情况.然后在网上试了很多方式.这里做一个记录 二.加入本地依赖包 <dependency> < ...
- 理解依赖注入(Dependency Injection)
理解依赖注入 Yii2.0 使用了依赖注入的思想.正是使用这种模式,使得Yii2异常灵活和强大.千万不要以为这是很玄乎的东西,看完下面的两个例子就懂了. class SessionStorage { ...
- python常用模块详解2
序列化模块补充: 1.json格式的限制,json格式的key必须是字符串数据类型 2.json格式的字符串必须是"" 如果数字是key,那么dump之后会强转成字符串数据类型 i ...
- JMeter与WireShark
最近在学习JMeter,刚学了一点皮毛,就掉入了WireShark的坑,我发现在学习的道路上就是不断的给自己挖坑,之前在学习LoadRunner的道路上,遇到的坑更大,就单纯的安装LR就耗费了两个星期 ...
- Vue学习计划基础笔记(一) - vue实例
最近又重新看vue的文档了,计划是别人写的,之前看过一次,没有考虑太多,只考虑看懂能用就好.看完之后写过写demo,现在是零实际项目经验的,所以这一次打算细看,算是官方文档的二次产物吧,但是不是全部直 ...
- Parcel 打包器简单使用记录
本文是构造 UI 轮子过程中搭建项目初始化时使用 Parcel 作为打包器的简要使用记录. 安装 参考 官方文档 使用 npm 进行 parcel-bundler 的安装. npm i -D parc ...