刚做完一个SharePoint solution,想在里边用依赖注入,一直没找到方法,就用微软的依赖注入框架采用locator的模式去解析服务。
今天又想到了这个事,又是查找资料,想想AI时代,问了问ChatGPT,自己抱着试一试的心态,发现还真可以用。
直接用Autofac就行了。
写了个测试代码,先定义一个服务接口。
[ServiceContract] public interface IAutofacTest { [OperationContract, WebInvoke(Method = "GET", UriTemplate = "TestGet", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] OutputTest TestGet(); } public class OutputTest { public string Name { get; set; } }
在写个简单的实现。
[ServiceBehavior(IncludeExceptionDetailInFaults = true)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class AutofacTest : IAutofacTest { public AutofacTest() { } private readonly IMyService _myservice; public AutofacTest(IMyService myservice) { _myservice = myservice; } public OutputTest TestGet() { return new OutputTest() { Name = _myservice == null ? "abc": _myservice.Do() }; } }
自定义一个factory。
public class CustomMultipleBaseAddressAutofacFactory: MultipleBaseAddressWebServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { if (IoCContainer.GetContainer() == null) { IoCContainer.Initialize(); } var host = new CustomMultipleBaseServiceHost(serviceType, baseAddresses); host.AddDependencyInjectionBehavior<IAutofacTest>(IoCContainer.GetContainer()); return host; } }
IOC container:
public static class IoCContainer { private static IContainer _container; public static void Initialize() { var builder = new ContainerBuilder(); builder.RegisterType<AutofacTest>().As<IAutofacTest>().InstancePerLifetimeScope(); builder.RegisterType<MyService>().As<IMyService>().InstancePerLifetimeScope(); _container = builder.Build(); } public static T Resolve<T>() { return _container.Resolve<T>(); } public static IContainer GetContainer() { return _container; } }
加入factory。
<%@ ServiceHost Language="C#" Debug="true" Service="Solution.ISAPI.AutofacTest,$SharePoint.Project.AssemblyFullName$" CodeBehind="AutofacTest.svc.cs" Factory="Solution.CustomMultipleBaseAddressAutofacFactory, $SharePoint.Project.AssemblyFullName$"
deploy 一下。
请求SharePoint wcf地址 site/_vti_bin/xx/AutofacTest.svc/TestGet
正常返回:
{ "TestGetResult": { "Name": "hello" } }

浙公网安备 33010602011771号