且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我们可以在wcf服务中使用简单的注入器进行依赖注入吗?如何?

更新时间:2023-10-18 22:24:10

我们可以在wcf服务中使用简单的注入器进行依赖项注入.这是我的演示.安装此NuGet程序包后,必须通过调用SimpleInjectorServiceHostFactory.SetContainer方法在应用程序的启动路径中对其进行初始化:

We can use simple injector for dependency injection in wcf services.Here is my demo. After installing this NuGet package, it must be initialized in the start-up path of the application by calling the SimpleInjectorServiceHostFactory.SetContainer method:

     protected void Application_Start(object sender, EventArgs e)
    {

        var container = new Container();
        container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

        container.RegisterWcfServices(Assembly.GetExecutingAssembly());


        container.Register<IDemo, Demo>();

        SimpleInjectorServiceHostFactory.SetContainer(container);
    }

对于每个服务类,应在每个服务类的.SVC文件中提供一个factory属性.例如:

For each service class, you should supply a factory attribute in the .SVC file of each service class. For instance:

    <%@ ServiceHost
Service="Demo_rest_IIS.Service1"
CodeBehind="Service1.svc.cs"
Factory="SimpleInjector.Integration.Wcf.SimpleInjectorServiceHostFactory,
    SimpleInjector.Integration.Wcf"%>

通过构造方法注入服务

     public class Service1 : IService1
     {
       private IDemo demo;
       public Service1(IDemo demo){
        this.demo = demo;
        }
     }

您可以参考以下链接:

https://github.com/simpleinjector/Documentation/blob/master/source/wcfintegration.rst