在C#中,使用Inversion of Control (IoC) 容器可以帮助我们更好地管理依赖关系。常用的IoC容器有Autofac、Castle Windsor、Ninject等。这里以Autofac为例,介绍如何进行配置。
首先,安装Autofac库。在Visual Studio中,通过NuGet包管理器搜索并安装Autofac。
创建一个Autofac模块。在项目中创建一个新的C#类,例如AppModule.cs
,并在该类中定义需要注册的类型和依赖关系。
using Autofac; public class AppModule : Module { protected override void Load(ContainerBuilder builder) { // 注册服务 builder.RegisterType<Service1>().As<IService>(); builder.RegisterType<Service2>().As<IService>(); // 注册控制器 builder.RegisterType<Controller1>().As<IController>(); } }
Program.cs
)中,创建一个Autofac容器并加载模块。using Autofac; class Program { static void Main(string[] args) { // 创建Autofac容器 var container = new ContainerBuilder(); // 加载模块 container.RegisterModule<AppModule>(); // 解析依赖关系 var service = container.Resolve<IService>(); var controller = container.Resolve<IController>(); // 使用依赖关系 controller.DoSomething(service); } }
TypedParameter
、NamedParameter
或ResolvedParameter
等方法。builder.Register((p, c) => new Service1("Dynamic parameter")).As<IService>();
As<T>
方法并指定优先级。builder.RegisterType<Service1>().As<IService>().WithPriority(1); builder.RegisterType<Service2>().As<IService>().WithPriority(2);
RegisterAssemblyModules
方法。container.RegisterAssemblyModules(typeof(AppModule).Assembly);
以上就是使用Autofac进行IoC配置的基本步骤。实际项目中,可能需要根据具体需求进行更复杂的配置。