Autofac 的点滴

泛型类型的注册和使用

public interface IRepository<T> where T:class
{
}

public interface ISchoolDetailRepository : IRepository<SchoolDetail>
{
}

public abstract class RepositoryBase<T> where T : class
{
private LearningCompactPilotContext _dataContext;
private readonly IDbSet<T> _dbset;
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
    DatabaseFactory = databaseFactory;
    _dbset = DataContext.Set<T>();
}

protected IDatabaseFactory DatabaseFactory
{
    get; private set;
}

protected LearningCompactPilotContext DataContext
{
    get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
}

//... more code
}

//如何注册

builder.RegisterGeneric(typeof(RepositoryBase<>))
   .As(typeof(IRepository<>));

//如何使用
public class SomeService
{
    private readonly IRepository<SomeEntity> _repository;

    public SchoolService(IRepository<SomeEntity> repository)
    {
        this._repository= repository;
    }
}

如何注入泛型的Nloggger<T>  AS ILogger(动态类型注入)

public class LoggingModule : Autofac.Module
{
  private static void InjectLoggerProperties(object instance)
  {
    var instanceType = instance.GetType();

    // Get all the injectable properties to set.
    // If you wanted to ensure the properties were only UNSET properties,
    // here‘s where you‘d do it.
    var properties = instanceType
      .GetProperties(BindingFlags.Public | BindingFlags.Instance)
      .Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0);

    // Set the properties located.
    foreach (var propToSet in properties)
    {
      propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null);
    }
  }

  private static void OnComponentPreparing(object sender, PreparingEventArgs e)
  {
    e.Parameters = e.Parameters.Union(
      new[]
      {
        new ResolvedParameter(
            (p, i) => p.ParameterType == typeof(ILog),
            (p, i) => LogManager.GetLogger(p.Member.DeclaringType)
        ),
      });
  }

  protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
  {
    // Handle constructor parameters.
    registration.Preparing += OnComponentPreparing;

    // Handle properties.
    registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
  }
}

相同接口不同实现的如何注册使用

适配模式和装饰模式注册

适配模式

var builder = new ContainerBuilder();

// Register the services to be adapted
builder.RegisterType<SaveCommand>()
       .As<ICommand>()
       .WithMetadata("Name", "Save File");
builder.RegisterType<OpenCommand>()
       .As<ICommand>()
       .WithMetadata("Name", "Open File");

// Then register the adapter. In this case, the ICommand
// registrations are using some metadata, so we‘re
// adapting Meta<ICommand> instead of plain ICommand.
builder.RegisterAdapter<Meta<ICommand>, ToolbarButton>(
   cmd => new ToolbarButton(cmd.Value, (string)cmd.Metadata["Name"]));

var container = builder.Build();

// The resolved set of buttons will have two buttons
// in it - one button adapted for each of the registered
// ICommand instances.
var buttons = container.Resolve<IEnumerable<ToolbarButton>>();

装饰模式

var builder = new ContainerBuilder();

// Register the services to be decorated. You have to
// name them rather than register them As<ICommandHandler>()
// so the *decorator* can be the As<ICommandHandler>() registration.
builder.RegisterType<SaveCommandHandler>()
       .Named<ICommandHandler>("handler");
builder.RegisterType<OpenCommandHandler>()
       .Named<ICommandHandler>("handler");

// Then register the decorator. The decorator uses the
// named registrations to get the items to wrap.
builder.RegisterDecorator<ICommandHandler>(
    (c, inner) => new CommandHandlerDecorator(inner),
    fromKey: "handler");

var container = builder.Build();

// The resolved set of commands will have two items
// in it, both of which will be wrapped in a CommandHandlerDecorator.
var handlers = container.Resolve<IEnumerable<ICommandHandler>>();

还是使用泛型

var builder = new ContainerBuilder();

// Register the open generic with a name so the
// decorator can use it.
builder.RegisterGeneric(typeof(CommandHandler<>))
       .Named("handler", typeof(ICommandHandler<>));

// Register the generic decorator so it can wrap
// the resolved named generics.
builder.RegisterGenericDecorator(
        typeof(CommandHandlerDecorator<>),
        typeof(ICommandHandler<>),
        fromKey: "handler");

var container = builder.Build();

// You can then resolve closed generics and they‘ll be
// wrapped with your decorator.
var mailHandlers = container.Resolve<IEnumerable<ICommandHandler<EmailCommand>>>();
 

参考

MVC 4 Autofac and Generic Repository pattern

log4net Integration Module

Adapters and Decorators

How do I pick a service implementation by context?

时间: 2024-09-30 09:52:52

Autofac 的点滴的相关文章

AutoFac Asp.Net Mvc

autofac依赖注入,帮我们实例化接口,无需使用传统的New 如: public class AutoFacController : Controller { public IPeople _people; public AutoFacController(IPeople people) { _people = people; } // GET: AutoFac public ActionResult Index() { ViewBag.test = _people.Getpeople();

[转]依赖注入框架Autofac的简单使用

Autofac是一款IOC框架,比较于其他的IOC框架,如Spring.NET,Unity,Castle等等所包含的,它很轻量级性能上也是很高的.于是,今天抽空研究了下它.下载地址:http://code.google.com/p/autofac/downloads/list 1)解压它的压缩包,主要看到Autofac.dll,Autofac.Configuration.dll,这也是本篇文章重点使用的Autofac的类库. 2)创建一个控制台工程,并且引用以上的DLL文件.创建一个数据库操作接

【翻译Autofac的帮助文档】1.入门指南

[写在前面]尝试做完一件工作之外自我觉得有意义的一件事,那就从翻译Autofac的帮助文档吧. 入门指南 将Autofac集成你的应用程序的步骤通常很简单,一般是: 时刻以IOC(控制反转)的思想来规划你的应用程序 在你的Porject中添加Autofac引用 按照如下步骤设计应用程序的启动环节 创建一个ContainerBuilder 向ContainerBuilder注册组件 通过ContainerBuilder的Build()方法获得Container(后续需用到) 在应用程序运行环节时,

用Autofac实现MVC5的IoC控制反转方法

Autofac跟Ninject一样,都是用于IOC,实现依赖注入的.主要有两个步骤,其余跟Ninject差不多. 1.主要的操作是在MVC项目下的Infrastructure(基础结构/公共建设)文件夹下,新建一人注册Autofac的IOC的类 namespace BookShop.WebUI.Infrastructure { public class AutofacReg { public static void RegisterDenpendencies() { var build = ne

问题:IIS部署 MVC项目 (autofac) 错误解决

http://www.cnblogs.com/yelaiju/p/3375168.html Could not load file or assembly 'System.Core, Version=2.0.5.0 和autofac冲突的问题 在部署到iis的时候会出现这个状况. 解决:下载安装这个补丁 http://support.microsoft.com/kb/2468871 http://www.microsoft.com/zh-cn/download/confirmation.aspx

NET Core 整合Autofac和Castle

NET Core 整合Autofac和Castle 阅读目录 前言: 1.ASP.NET Core中的Autofac 2.整合Castle的DynamicProxy 3.注意事项 回到目录 前言: 除了ASP.NETCore自带的IOC容器外,我们还可以使用其他成熟的DI框架,如Autofac,StructureMap等(笔者只用过Unity,Ninject和Castle). 回到目录 1.ASP.NET Core中的Autofac 首先在Project.json的Dependency节点为中添

autofac v4.0+通过配置文件的方式注册组件

最近在看李玉宝 / OpenAuth.Net的项目代码,新手表示看不懂.所以,不管三七二十一,模仿是最好的学习,于是我决定自己创建一个项目,把人家的代码一点一点拷贝过来,细细品味. 在研究的过程中,我发现大神用autofac是通过配置文件的方式.Autofac.Configuration的版本是V3.3,然后我创建的项目用的是V4.0.1. 本来是想用代码注册组件的,但是以看到大神是通过配置文件注册的,于是乎,不管三七二十一,我就定下了一个小目标,我要用v4.0.1版本来完成使用配置文件的方式来

Autofac 之 基于 Castle DynamicProxy2 的 Interceptor 功能

Autofac 结合 Castle DynamicProxy2 功能 Autofac 不仅作为轻量级高效的 IoC 容器,而且还能很好的与 Castle.DynamicProxy2 结合起来,实现 AOP 功能. 首先,我们需要定义拦截器,简单的定义可实现 Castle.DynamicProxy.IInterceptor 接口即可. 添加拦截器   定义好了拦截器后,如何应用到相关对象呢?有两种方式: 1)使用 Autofac.Extras.DynamicProxy2.InterceptAttr

浅析依赖注入框架Autofac的使用

Autofac是一款IOC框架,比起Spring.NET,Unity,Castle等等框架,它很轻量级且性能也很高,下面小编给大家介绍下依赖注入框架Autofac的使用. 下面通过代码给大家分享下依赖注入框架Autofac的使用,具体如下所示:  Autofac是一款IOC框架,比较于其他的IOC框架,如Spring.NET,Unity,Castle等等所包含的,它很轻量级性能上也是很高的. 1)解压它的压缩包,主要看到Autofac.dll,Autofac.Configuration.dll,