Unity容器声明周期管理
Having said that, here is a solution that you can use with the Unity container:
Create some custom attributes for the different lifetime styles that you want to have like this:
[AttributeUsage(AttributeTargets.Class)]
public class SingletonAttribute : Attribute
{ } [AttributeUsage(AttributeTargets.Class)]
public class TransientAttribute : Attribute
{ }
You can have these attributes in some common library and reference it from your service class libraries.
Then, apply these attributes to your service classes in your class libraries like in your question:
[Singleton]
public class ServiceImplA : IService
{} [Transient]
public class ServiceImplB : IService
{}
Now, define a helper method that can get the lifetime manager based on reflection like this:
public static LifetimeManager GetLifeTimeManager<T>()
{
Type type = typeof (T); if(type.GetCustomAttribute(typeof(TransientAttribute)) != null)
return new TransientLifetimeManager(); if (type.GetCustomAttribute(typeof(SingletonAttribute)) != null)
return new ContainerControlledLifetimeManager(); //Add more cases here return new TransientLifetimeManager(); //Default is transient
}
And use it like this:
container.RegisterType<IService, ServiceImplA>(GetLifeTimeManager<ServiceImplA>());
By the way, this solution is DI container independent. I mean that the attributes themselves are not specific to any container. It is the GetLifeTimeManager
helper method that is specific to the Unity container. But you can use other DI containers and define similar helper methods for them.
You can also create extension methods to hide the invocation of the helper method like this:
public static IUnityContainer RegisterTypeWithLifeTime<TFrom, TTo>(this IUnityContainer container) where TTo : TFrom
{
return container.RegisterType<TFrom, TTo>(GetLifeTimeManager<TTo>());
}
And use it like this:
container.RegisterTypeWithLifeTime<IService, ServiceImplA>();
You just need to constrain the types returned to types that are annotated with the Singleton
attribute:
container.RegisterTypes(
AllClasses.FromLoadedAssemblies()
.Where(t => t.GetCustomAttributes<SingletonAttribute>(true).Any()),
WithMappings.FromMatchingInterface,
WithName.Default,
WithLifetime.ContainerControlled);
You could register everything and then overwrite the registration for any singletons with a ContainerControlledLifetimeManager
:
// Register All Types by Convention by default
container.RegisterTypes(
AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default,
WithLifetime.Transient); // Overwrite All Types marked as Singleton
container.RegisterTypes(
AllClasses.FromLoadedAssemblies()
.Where(t => t.GetCustomAttributes<SingletonAttribute>(true).Any()),
WithMappings.FromMatchingInterface,
WithName.Default,
WithLifetime.ContainerControlled,
null,
true); // Overwrite existing mappings without throwing
Another Container:
using System;
using System.Reflection;
using SimpleInjector.Advanced; // Attribute for use by the application
public enum CreationPolicy { Transient, Scoped, Singleton } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,
Inherited = false, AllowMultiple = false)]
public sealed class CreationPolicyAttribute : Attribute {
public CreationPolicyAttribute(CreationPolicy policy) {
this.Policy = policy;
} public CreationPolicy Policy { get; private set; }
} // Custom lifestyle selection behavior
public class AttributeBasedLifestyleSelectionBehavior : ILifestyleSelectionBehavior {
private const CreationPolicy DefaultPolicy = CreationPolicy.Transient; public Lifestyle SelectLifestyle(Type serviceType, Type implementationType) {
var attribute = implementationType.GetCustomAttribute<CreationPolicyAttribute>()
?? serviceType.GetCustomAttribute<CreationPolicyAttribute>(); switch (attribute != null ? attribute.Policy : DefaultPolicy) {
case CreationPolicy.Singleton: return Lifestyle.Singleton;
case CreationPolicy.Scoped: return Lifestyle.Scoped;
default: return Lifestyle.Transient;
}
}
} // Usage
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); container.Options.LifestyleSelectionBehavior =
new AttributeBasedLifestyleSelectionBehavior(); container.Register<IUserContext, AspNetUserContext>(); // Usage in application
[CreationPolicy(CreationPolicy.Scoped)]
public class AspNetUserContext : IUserContext {
// etc
}
Unity容器声明周期管理的更多相关文章
- 004-docker命令-容器生命周期管理、容器操作
1.容器生命周期管理 docker run :创建一个新的容器并运行一个命令 语法:docker run [OPTIONS] IMAGE [COMMAND] [ARG...] OPTIONS说明: - ...
- Salesforce LWC学习(四) 父子component交互 / component声明周期管理 / 事件处理
我们在上篇介绍了 @track / @api的区别.在父子 component中,针对api类型的变量,如果声明以后就只允许在parent修改,son component修改便会导致报错. sonIt ...
- 044、vloume声明周期管理(2019-03-07 周四)
参考https://www.cnblogs.com/CloudMan6/p/7214828.html 如果Data Volume 中存放的是重要的应用数据,如何管理volume对应用至关重要. ...
- Docker系列02: 容器生命周期管理 镜像&容器
A) Docker信息1. 查看docker运行状态 systemctl status docker docker.service - Docker Application Container Eng ...
- Docker 容器生命周期管理命令
docker run 命令 -d: 后台运行容器,并返回容器ID: -i: 以交互模式运行容器,通常与 -t 同时使用: -t: 为容器重新分配一个伪输入终端,通常与 -i 同时使用: --name= ...
- rxjava封装,RxBus封装(上线项目集成,声明周期管理,处理溢出内存,支持同时多个请求。)
Github地址 RxLibrary工程:1.rxjava2 + retrofit2的封装,常用的请求(Get,Post,文件上传,文件下载),防止内存泄漏,简单便捷,支持自定义loading等属性. ...
- Docker容器与镜像管理
目录 容器管理 运行容器 容器的启停操作 容器导入导出 容器生命周期管理 容器资源限制 内存限制 CPU限制 io 限制 镜像管理 镜像命名规范 镜像基本操作 容器管理 运行容器 1.运行一个容器示例 ...
- Castle IOC容器组件生命周期管理
主要内容 1.生命处理方式 2.自定义生命处理方式 3.生命周期处理 一.生命处理方式 我们通常创建一个组件的实例使用new关键字,这样每次创建出来的都是一个新的实例,如果想要组件只有一个实例,我们会 ...
- [原创]java WEB学习笔记31:会话与状态管理 session机制 概述(定义,session机制,session的声明周期,保存session的方式,Session的创建与删除)
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
随机推荐
- hdu 1004 Let the Balloon Rise strcmp、map、trie树
Let the Balloon Rise Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Oth ...
- Phpstorm Alt+Enter 自动导入类
很方便!!!能够自动提示哪些类没有自动加载!!!然后Alt+Enter进行安装!!!
- Android静态变量的生命周期
Android是用Java开发,其静态变量的生命周期遵守Java的设计.我们知道静态变量是在类被load的时候分配内存的,并且存在于方法区.当类 被卸载的时候,静态变量被销毁.在PC机的客户端程序中, ...
- ARIMA模型——本质上是error和t-?时刻数据差分的线性模型!!!如果数据序列是非平稳的,并存在一定的增长或下降趋势,则需要对数据进行差分处理!ARIMA(p,d,q)称为差分自回归移动平均模型,AR是自回归, p为自回归项; MA为移动平均,q为移动平均项数,d为时间序列成为平稳时所做的差分次数
https://www.cnblogs.com/bradleon/p/6827109.html 文章里写得非常好,需详细看.尤其是arima的举例! 可以看到:ARIMA本质上是error和t-?时刻 ...
- 99%的人都理解错了HTTP中GET与POST的区别(转自知乎)
作者:Larry链接:https://zhuanlan.zhihu.com/p/22536382来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. GET和POST是HTT ...
- 使用QQ邮箱SMTP服务的javamail配置
最近做一个小项目要用到JAVA的邮箱的发送功能.遇到一些坑这里记录分享一下:QQ群交流:697028234 1.QQ邮箱一定要设置开通SMTP/POP这项.并生成授权码. 2.用MAVEN生成一个QU ...
- String类的concat()方法
String类的concat()方法: public class MyClass { public static void main(String[] args) { String str1=&quo ...
- SharePoint 2013的100个新功能之搜索(一)
一:新的搜索架构 SharePoint 2013中将最好的两个搜索引擎"SharePoint搜索"和"SharePoint FAST搜索服务"整合到了一个搜索引 ...
- kindEditor富文本编辑器
用法参考:http://kindeditor.net/docs/usage.html 一.使用 . 修改HTML页面 在需要显示编辑器的位置添加textarea输入框. <textarea i ...
- LRY_FX_Assist(辅助EA)
功能说明 辅助EA就是别的EA没有功能用这个EA来弥补,比如说风控设置(预付款.浮亏.加仓层数等达到多少进行操作),移动止损(包括隐藏移动止损),启动马丁加仓等.这个EA不能自己独立开单,只能辅助其它 ...