使用Autofac注册对象,使其像控制器一样工作(Register object with Autofac so it acts like a controller)

编程入门 行业动态 更新时间:2024-10-08 18:41:40
使用Autofac注册对象,使其像控制器一样工作(Register object with Autofac so it acts like a controller)

我有一个我正在调用EndPointConfigurator的类,我想在其中注入一些东西,特别是一个工作单元,并在该类中使用它。

public class EndPointConfigurator { private static UnitOfWork _unitOfWork; public EndPointConfigurator(IUnitOfWork uow) { _unitOfWork = (UnitOfWork)uow; } //use unit of work }

我这样注册我的控制器:

builder.RegisterAssemblyTypes(getExecutingAssembly) .Where(t => t.Name.EndsWith("Controller", StringComparison.InvariantCulture));

我想知道注册这个类的最佳方法是什么,以便它可以像控制器那样注入一些东西。 控制器没有接口,我不想或不需要这个类的接口,因为我不需要在任何地方注入它。

I have a class that I'm calling EndPointConfigurator and I would like to inject some things, specifically a Unit of Work, into it and use it in that class.

public class EndPointConfigurator { private static UnitOfWork _unitOfWork; public EndPointConfigurator(IUnitOfWork uow) { _unitOfWork = (UnitOfWork)uow; } //use unit of work }

I register my controllers as such:

builder.RegisterAssemblyTypes(getExecutingAssembly) .Where(t => t.Name.EndsWith("Controller", StringComparison.InvariantCulture));

I was wondering what is the best way to register this class so that it can get something injected into it like controllers do. Controllers don't have interfaces and I don't want or need an interface for this class because I won't be needing to inject it anywhere.

最满意答案

您可以将类型注册为自己:

builder.RegisterType<EndPointConfigurator>().As<EndpointConfigurator>();

要么

builder.RegisterType<EndPointConfigurator>().AsSelf();

或者,如果您未指定任何服务, Autofac将自动注册为自己

builder.RegisterType<EndPointConfigurator>();

我更喜欢第一种解决方案,这样我们明确告诉容器我们想要做什么。

You can register the type as itself :

builder.RegisterType<EndPointConfigurator>().As<EndpointConfigurator>();

or

builder.RegisterType<EndPointConfigurator>().AsSelf();

or if you don't specify any service, Autofac will automatically register as itself

builder.RegisterType<EndPointConfigurator>();

I prefer the first solution, this way we explicity tell the container what we want to do.

更多推荐

本文发布于:2023-04-29 09:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:使其   控制器   对象   工作   Autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!