.net 版本: .Net Framework 4.8
新建项目,添加相应引用
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net48</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Topshelf" Version="4.2.1" />
<PackageReference Include="Topshelf.Owin" Version="1.4.39" />
<PackageReference Include="Autofac.WebApi2.Owin" Version="5.0.0" />
<PackageReference Include="Volo.Abp.Autofac" Version="2.9.0" />
</ItemGroup>
</Project>
引用说明
引用 | 说明 |
---|---|
Topshelf | 用于迅速架设与开发Windows服务 |
Topshelf.Owin | Topshelf的Owin扩展 |
Autofac.WebApi2.Owin | AutoFac的 WebAPI 和 Owin扩展 |
Volo.Abp.Autofac | Abp框架 的 Autofac扩展 |
建立 ABP模块类
[DependsOn(typeof(AbpAutofacModule))]
public class F48Module : AbpModule{ }
windows服务类
class YourService
{
public void Start()
{
}
public void Stop()
{
}
}
Main入口
static void Main(string[] args)
{
using (var application = AbpApplicationFactory.Create<F48Module>(options => //控制台模式启用ABP
{
options.Configuration.CommandLineArgs = args;
options.UseAutofac(); //abp 使用 autofac
}))
{
application.Initialize();
HostFactory.Run(c =>
{
c.RunAsNetworkService();
c.Service<YourService>(s => //YourService似乎没什么用,但不加会出错
{
s.ConstructUsing(() => new YourService());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
s.OwinEndpoint(app =>
{
app.ConfigureAppBuilder(Configuration);
app.Domain = "localhost"; //地址
app.Port = 8081; //端口
});
});
});
void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter()); //使用json格式
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.Formatting = Formatting.Indented;
jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//首字母小写
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}", //路由样式
defaults: new {id = RouteParameter.Optional}
);
var lifeTimeScope = application.ServiceProvider.GetService<ILifetimeScope>(); //使用Volo.Abp.Autofac 里的ILifetimeScope
app.UseAutofacMiddleware(lifeTimeScope); //注册autofac中间件
app.UseAutofacWebApi(config); //autofac 的webapi相关设置
app.UseWebApi(config); //启用web api
}
}
}
测试Controller
public interface ITest
{
string Str();
}
class Test : ITest, ITransientDependency
{
public string Str()
{
return nameof(Test);
}
}
public class ValuesController : ApiController
{
private readonly ITest _test;
public ValuesController(ITest test)
{
_test = test;
}
// GET api/values/5
public string Get(int id)
{
return _test.Str();
}
}
网友评论