在mVC 4 中用 unity 进行依赖注入

Unity——VContainer的依赖注入 ​由于我们使用的是Unity,而主要的Mono不支持构造函数。所以我们这里选择注入方式主要是特性注入和方法注入三、VContainer案例1、注册类型2、方法注入这里实现接口IStartable和ITickable。它是不依赖于Mono的接口,因此性能上更好,另一方面,IStartable与Mono的Start,ITickable与Mono的Update都是相同的。(2)基础MVC功能:Model层View层Control层。 阅读详情

在 mvc 4 中使用 unity 进行依赖注入

关于依赖注入的概念,这里就不再叙述了,我们用 mvc 4 结合 unity,使用构造函数来进行依 赖注入。具体步骤如下: 1. 首先建立 一个 mvc 项目, 选择 basic

创建好后,完整的项目应该是这样的:

2. 创建 Home控制器, 并添加 index 视图

3.创建 UserInfo 类, 和 Iuser 接口以及 UserService类,UserService 实现Iuser 接口中 的方法, 其中的业务逻辑自己可以根据具体的情况来实现

4.打开 Nuget 程序管理包, 在搜索框中输入 unity ,并下载安装,具体如下图:

5. 创建一个 依赖解析容器,并实现接口IDependencyResolver 中两个重要的方法 object GetService(Type serviceType) IEnumerable<object> GetServices(Type serviceType) 这两个方法就是返回所依赖的服务的对象

 /// <summary>
   ///  Dependency Injection  Resolver Container 
   /// </summary>
    public class UnityResolver : IDependencyResolver
    {
        protected IUnityContainer container;

        public UnityResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this.container = container;
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }

    }

 

6. 在 app_start 中添加一个 unityConfig 配置文件

 在这个文件中声明一个静态的没有返回值的方法,RegisterComponents,实例化一个解析容器  (也是刚才所添加的解析容器),然后将所依赖的接口和实现类在这里进行注册。  container.RegisterType<IUserInfo, UserInfoService>( new  HierarchicalLifetimeManager());  最后调用 DependencyResolver对象的 SetResolver方法 来保存刚才的注册。

public static void RegisterComponents()
        {
			var container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            // e.g. container.RegisterType<ITestService, TestService>();
            
            container.RegisterType<IUserInfo, UserInfoService>( new HierarchicalLifetimeManager());

            DependencyResolver.SetResolver(new UnityResolver(container));
            
        }

 

7. 在 global.cs 中注册 UnityConfig 配置文件

   UnityConfig.RegisterComponents();

 

8. 在Home 控制器中使用构造函数注入

      IUserInfo userinfoService;
      public HomeController( IUserInfo userinfoService)
      {
        // 依赖注入
        this.userinfoService = userinfoService;
      }

 

 重新生成一下项目,如果没有错误,启动运行,我们将会看到样的界面:

 源码下载: 下载源码


【Unity每篇一个知识点】:MVC设计模式 MVC设计模式 阅读详情

相关推荐

Unity MVC实现依赖注入实例

Unity MVC实现依赖注入实例

在 mvc 4 中使用 unity 进行依赖注入

在 mvc 4 中使用 unity 进行依赖注入 关于依赖注入的概念,这里就不再叙述了,我们用 mvc 4 结合 unity,使用构造函数来进行依 赖注入。具体步骤如下: 1. 首先建立 一个 mvc 项目, 选择 basic 创建好后,完整的项目应该是这样的: 2. 创建 Home控制器, 并添加 index 视图 3.创建 UserInfo 类, 和 Iuser 接口以及 Us...

weixin_30878361的博客 179

mvc4 ioc 依赖注入简单示例实现

本demo采用vs2010旗舰版开发,实现了在mvc4中利用unity实现对抽象接口到Controller里的注入。参考资料《蒋金楠》博客园博客和互联网资源。

Asp.Net MVC5 使用Unity 实现依赖注入

到这里安装完毕会提示一个redme.txt,说 把UnityConfig.RegisterComponents(); 放到下图的位置,我们照做即可。 然后我们看一下这个UnityConfig 中是什么。 例子说明我们这里是注册对应关系的。所以我们就以例子的中的ITestService 和TestService 分别建立 接口和实现类...

SYY18012524183的博客 305

Unity实现依赖注入

该项目实例主要演示Unity容器实现依赖注入

使用Unity.MVC3在asp.net mvc3中实现依赖注入

使用Unity.MVC3在asp.net mvc3中实现依赖注入 有具体使用步骤

Asp.net MVC源码分析--DependencyResolver与Service Location

这一篇我们讲解如何利用DependencyResolver来定位我们的自定义服务(service)也就查找Controller. 首先让我们来看一下DependencyResolver 的实现。 DependencyResolver.cs View Code 1 public class DependencyResolver { 2 // Static ...

anweijian3604的博客 404

ASP.NET MVC如何使用Unity实现Ioc详解

为什么有这篇文章 最近在学ASP.NET MVC项目中使用Ioc,选用了Unity作为依赖注入的容器组件,在网上找了相关的文章简单实现了依赖注入,但想用文件配置的方式进行容器注入的注册,发现相关的文章实现的方式不适用,因为网上的文章大多是使用Unity 4.0.1的版本,而目前最新的Unity版本是5.8.6,使用配置进行容器注入的代码已然不同。 Ioc和Unity IOC(Inversion of Control),即“控制反转”,是一种设计思想。有了IoC后,把创建和查找依赖对象的控制权交给了容器,由容器进行注入组合对象,所以对象与对象之间是松散耦合,这样也方便测试,利于功能复用,更重要的

IoC实践--ASP.NET MVC5 采用Unity依赖注入Controller详解

我之前写的文章一般都有通过Autofac来实现IoC,这次我来换一个框架,体会一下ASP.NET mvc5 采用Unity依赖注入Controller。此之前说说一下Unity框架。Unity是微软Patterns &amp; Practices团队所开发的一个轻量级的,并且可扩展的依赖注入(Dependency Injection)容器,它支持常用的三种依赖注入方式:构造器注入(Construc...

crazyliyang的专栏 1390

Arch Linux双系统安装避坑指南:从Windows分区到桌面环境全流程

本文提供了一份详尽的Arch Linux与Windows双系统安装避坑指南。内容涵盖从安装前的UEFI环境确认、BitLocker处理、分区规划,到Live环境进入、基础系统安装、GRUB引导配置,再到显卡驱动安装、KDE/GNOME桌面环境部署及中文化设置的全流程。重点解决了双系统安装中的核心痛点,帮助用户在不破坏现有Windows系统的前提下,顺利完成Arch Linux的安装。

nice1的博客 540

【Matlab/simulink/carsim】再生制动

【Matlab/simulink/carsim】再生制动

weixin_62311849的博客 626

.Net IOC框架入门之一 Unity

一、概述   IOC:英文全称:Inversion of Control,中文名称:控制反转,它还有个名字叫依赖注入(Dependency Injection)。  作用:将各层的对象以松耦合的方式组织在一起,解耦,各层对象的调用完全面向接口。当系统重构的时候,代码的改写量将大大减少。  依赖注入: 当一个类的实例需要另一个类的实例协助时,在传统的程序设计过程中,通常有调用者来创建被调用者的...

weixin_33911824的博客 272

DID实战指南:从平行趋势检验到PSM-DID的Stata全流程解析

本文详细解析了双重差分法(DID)在政策评估中的应用,从平行趋势检验到PSM-DID的Stata全流程操作。通过实例演示和代码示例,帮助研究者掌握DID方法的核心逻辑、前提条件验证及稳健性检验技巧,提升因果推断研究的准确性。

weixin_29234239的博客 753

MVC5 采用Unity依赖注入管理

MVC5 采用Unity依赖注入1. 定义Model2. 定义SysUser数据访问的接口3. 定义实现接口的实体类4. 创建Core项目5. NuGet安装6. 构建Controller7. 依赖注册生效 Unity是微软Patterns & Practices团队所开发的一个轻量级的,并且可扩展的依赖注入(Dependency Injection)容器,它支持常用的三种依赖注入方式:构...

wxm2106的博客 461

《UE4游戏开发》之 《音效系统的实现》

音效系统需要负责管理什么事情: 1.1 确定声音控制的分类:如背景音乐、技能音效、界面音效、角色配音等,不同游戏对声音有不同的分类 1.2 控制每个分类的声音的开启与关闭,以及调节每个分类声音的大小 解决如何分类: 2.1 首先需要知道ue4为声音分类提供了什么:SoundClass通常需要一个根分类【SC_RPG_Master】,便于总体控制音效,以及指定引擎默认启动的音效 打开SoundClass资产【SC_RPG_Master】,对根控制的设置,将逐级传递并按比例进行设置,以此达到控制一类声音的目的.

qq_21919621的博客 2131

学习笔记( 11 ) - 解决:finalshell连接虚拟机(ubuntu)超时,主机ping不通虚拟机,主机没有VMnet8网卡, Connection refused: connect

解决:finalshell连接虚拟机(ubuntu)超时,主机ping不通虚拟机,主机没有VMnet8网卡, Connection refused: connect

烟溪彭于晏的博客 2万+

Asp.Net MVC4 使用Unity 实现依赖注入

项目创建参考 上一篇 《《Asp.Net MVC5 使用Unity 实现依赖注入》》, 不同的是这里是 Unity.MVC4 装好后会出现 然后示例说在这里写对应关系 同样我们使用ITestService和TestService 做测试。 运行项目。 同样成功了。这里我们需要注意的是 MVC4和MVC5的结构是...

SYY18012524183的博客 302

跟着团子学SAP CO:基于成本的完工百分比结算:Cost-based POC(以项目为例)

本文以英国及北美会计准则下的基于成本的POC的销售型项目结算对PS模块中的完工百分比进行介绍

Lucas1211的博客 2万+

ASP.NET MVC中的依赖倒置IOC/依赖注入DI, (MircroSoft.Practices.Unity)与asp.net mvc 3的融合

基本:服务定位器和依赖注入使用了微软的MircroSoft.Practices.Unity框架. 目的:配合asp.net mvc 3实现一套框架,封装变化,松耦合,依赖注入但不使用配置文件. 思想:使用MircroSoft.Practices.Unity

LeeWhoee University 4508

在 RAP 里把编号这件事做得既优雅又合规:Early Numbering 与 Late Numbering 的落地指南

本文探讨了 SAP RAP 框架中的三种主键编号策略及其适用场景。文章首先指出传统 ABAP 应用中主键处理的局限性,详细分析了早期编号(外部/内部)和延迟编号的差异,强调延迟编号在避免业务断号方面的优势。通过 Partner 业务对象案例,文章演示了延迟编号的实现方法,包括行为定义配置、保存类实现和编号分配逻辑。同时指出测试中常见的校验陷阱,并提醒生产环境应避免简单的 MAX+1 方案,建议采用原子取号机制确保并发安全。全文从业务合规性和技术实现两个维度,为 RAP 应用的编号策略选择提供了实用指导。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1860

芒果YOLOv11改进175:DCNv4卷积,全网首发纯Pytorch实现代码,无需cuda编译|即插即用,一键运行:高效可变形卷积网络:重新思考视觉应用的动态和稀疏算子

芒果YOLOv11改进:DCNv4卷积,全网首发纯Pytorch实现代码,无需cuda编译|即插即用,一键运行:高效可变形卷积网络:重新思考视觉应用的动态和稀疏算子

包括YOLOv5、YOLOv7、YOLOv8等模型改进 1311

使用Unity.Mvc3实现依赖注入简介

开始使用Unity.Mvc3 本文一步一步演示如何在MVC3项目中使用Unity.Mvc3实现依赖注入。 先创建一个基本的MVC3项目。 Figure 1: The Visual Studio 2010 New Project Dialog Figure 2: The Visual Studio 2010 New ASP.NET MVC3 Internet Applicatio

litdwg的学习轨迹 1716

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

使用Unity 实现依赖注入

Unity是Unity是微软patterns& practices组用C#实现的轻量级,可扩展的依赖注入容器,它为方便开发者建立松散耦合的应用程序, 有以下优点:         1.简化了对象的创建,特别是针对分层对象结构和依赖关系;    2.需求的抽象,允许开发人员在运行时或配置文件中指定依赖关系,简化横切关注点的管理;    3.推迟为容器配置组件的时机,增加了灵活性;   

Andrewniu的博客 1178

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

MVC5+Unity4.0注入依赖学习

MVC5+Unity4.0注入依赖学习概念: Unity是一个轻量级的可扩展的依赖注入容器,支持构造函数,属性和方法调用注入。Unity可以处理那些从事基于组件的软件工程的开发人员所面对的问题。构建一个成功应用程序的关键是实现非常松散的耦合设计。松散耦合的应用程序更灵活,更易于维护。这样的程序也更容易在开发期间进行测试。你可以模拟对象,具有较强的具体依赖关系的垫片(轻量级模拟实现)

灵猪谁仰的专栏 2557

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

.NET依赖注入插件Unity的使用

Unity是微软模式与实践团队开发的一个轻量级、可扩展的依赖注入容器。下面我结合一个简单的MVC项目实现Unity的配置和使用。 1. 首先我们创建一个MVC4的解决方案,并创建如下的项目 IBaseData是接口项目,包含了一个接口类,以及Model(数据访问使用EF) 接口中定义了一些方法 如下:我们将在业务类中实现具体业务 ...

andy20160821的博客 360

ASP.NET MVC 4和ASP.NET Web API中的Unity

Thought this will help someone who wants to learn Unity framework in ASP.NET MVC 4 and ASP.NET Web API. Since the controllers are called directly by the MVC framework and as soon ...

cunchi8090的博客 178
上一篇: 接口与抽象类的区别
下一篇: web 跨域请求共享资源(OCRS)
SpringFiled
博客等级 码龄15年 9粉丝 78原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址