在ASP.NET Core中,我有准备在启动时进行注入的服务:
/**
* Disconnect
*
* @param address Mac Address
*/
public void disConnectDevice(String address) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BluetoothGatt mBluetoothGatt = device.connectGatt(this, false, gattCallback);
mBluetoothGatt.disconnect(); // Don't do this. Delete this line.
}
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
gatt.disconnect(); // add code.
gatt.close();
}
};
如果我调用API,它将启动。 但是,我希望它可以事先进行初始化(当应用启动时)。 我只是在控制器中放置一个断点,看看是否会发生这种情况。
答案 0 :(得分:3)
AddSingleton
方法可以使用类型或对象。所以你可以简单地做:
public void ConfigureServices(IServiceCollection services)
{
var serviceInstance = new Service();
serviceInstance.DoWhatever();
services.AddSingleton<IService, serviceInstance>();
services.AddMvc();
}
答案 1 :(得分:1)
ASP.NET Core应用程序使用启动class
,按照惯例将其命名为Startup
。 Startup
类:
ConfigureServices
会调用 Configure
和runtime
:
public class Startup
{
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
}
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
...
}
}
使用 WebHostBuilderExtensions UseStartup方法指定Startup类:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
**.UseStartup<Startup>();**
}
因此,如果您想在Startup
的项目启动时进行校准,请将您的方法放在Confirgure
祝你好运。
答案 2 :(得分:0)
您可以尝试将初始化逻辑放在构造函数中,这样就不必担心调用“适当的方法”。如果您的服务依赖于另一项服务才能正常运行,这也将为您提供帮助。万岁依赖注入:)